Skip to main content

rustc_lint/
builtin.rs

1//! Lints in the Rust compiler.
2//!
3//! This contains lints which can feasibly be implemented as their own
4//! AST visitor. Also see `rustc_session::lint::builtin`, which contains the
5//! definitions of lints that are emitted directly inside the main compiler.
6//!
7//! To add a new lint to rustc, declare it here using [`declare_lint!`].
8//! Then add code to emit the new lint in the appropriate circumstances.
9//!
10//! If you define a new [`EarlyLintPass`], you will also need to add it to the
11//! [`crate::early_lint_methods!`] invocation in `lib.rs`.
12//!
13//! If you define a new [`LateLintPass`], you will also need to add it to the
14//! [`crate::late_lint_methods!`] invocation in `lib.rs`.
15
16use std::fmt::Write;
17
18use ast::token::TokenKind;
19use rustc_abi::BackendRepr;
20use rustc_ast::tokenstream::{TokenStream, TokenTree};
21use rustc_ast::visit::{FnCtxt, FnKind};
22use rustc_ast::{self as ast, *};
23use rustc_ast_pretty::pprust::expr_to_string;
24use rustc_attr_parsing::AttributeParser;
25use rustc_errors::{Applicability, Diagnostic, msg};
26use rustc_feature::GateIssue;
27use rustc_hir::attrs::{AttributeKind, DocAttribute};
28use rustc_hir::def::{DefKind, Res};
29use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
30use rustc_hir::intravisit::FnKind as HirFnKind;
31use rustc_hir::{self as hir, Body, FnDecl, ImplItemImplKind, PatKind, PredicateOrigin, find_attr};
32use rustc_middle::bug;
33use rustc_middle::lint::LevelAndSource;
34use rustc_middle::ty::layout::LayoutOf;
35use rustc_middle::ty::print::with_no_trimmed_paths;
36use rustc_middle::ty::{self, AssocContainer, Ty, TyCtxt, TypeVisitableExt, Upcast, VariantDef};
37// hardwired lints from rustc_lint_defs
38pub use rustc_session::lint::builtin::*;
39use rustc_session::lint::fcw;
40use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass};
41use rustc_span::edition::Edition;
42use rustc_span::{DUMMY_SP, Ident, InnerSpan, Span, Spanned, Symbol, kw, sym};
43use rustc_target::asm::InlineAsmArch;
44use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
45use rustc_trait_selection::traits;
46use rustc_trait_selection::traits::misc::type_allowed_to_implement_copy;
47use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
48
49use crate::errors::BuiltinEllipsisInclusiveRangePatterns;
50use crate::lints::{
51    BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDerefNullptr, BuiltinDoubleNegations,
52    BuiltinDoubleNegationsAddParens, BuiltinEllipsisInclusiveRangePatternsLint,
53    BuiltinExplicitOutlives, BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote,
54    BuiltinIncompleteFeatures, BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures,
55    BuiltinKeywordIdents, BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc,
56    BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns,
57    BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
58    BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub,
59    BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment,
60    BuiltinUnusedDocCommentSub, BuiltinWhileTrue, EqInternalMethodImplemented, InvalidAsmLabel,
61};
62use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext};
63#[doc = r" The `while_true` lint detects `while true { }`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run"]
#[doc = r" while true {"]
#[doc = r""]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" `while true` should be replaced with `loop`. A `loop` expression is"]
#[doc =
r" the preferred way to write an infinite loop because it more directly"]
#[doc = r" expresses the intent of the loop."]
static WHILE_TRUE: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "WHILE_TRUE",
            default_level: ::rustc_lint_defs::Warn,
            desc: "suggest using `loop { }` instead of `while true { }`",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
64    /// The `while_true` lint detects `while true { }`.
65    ///
66    /// ### Example
67    ///
68    /// ```rust,no_run
69    /// while true {
70    ///
71    /// }
72    /// ```
73    ///
74    /// {{produces}}
75    ///
76    /// ### Explanation
77    ///
78    /// `while true` should be replaced with `loop`. A `loop` expression is
79    /// the preferred way to write an infinite loop because it more directly
80    /// expresses the intent of the loop.
81    WHILE_TRUE,
82    Warn,
83    "suggest using `loop { }` instead of `while true { }`"
84}
85
86pub struct WhileTrue;
#[automatically_derived]
impl ::core::marker::Copy for WhileTrue { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for WhileTrue { }
#[automatically_derived]
impl ::core::clone::Clone for WhileTrue {
    #[inline]
    fn clone(&self) -> WhileTrue { *self }
}
impl ::rustc_lint_defs::LintPass for WhileTrue {
    fn name(&self) -> &'static str { "WhileTrue" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [WHILE_TRUE]))
    }
}
impl WhileTrue {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [WHILE_TRUE]))
    }
}declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
87
88impl EarlyLintPass for WhileTrue {
89    #[inline]
90    fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
91        if let ast::ExprKind::While(cond, _, label) = &e.kind
92            && let ast::ExprKind::Lit(token_lit) = cond.peel_parens().kind
93            && let token::Lit { kind: token::Bool, symbol: kw::True, .. } = token_lit
94            && !cond.span.from_expansion()
95        {
96            let condition_span = e.span.with_hi(cond.span.hi());
97            let replace = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}loop",
                label.map_or_else(String::new,
                    |label|
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}: ", label.ident))
                            }))))
    })format!(
98                "{}loop",
99                label.map_or_else(String::new, |label| format!("{}: ", label.ident,))
100            );
101            cx.emit_span_lint(
102                WHILE_TRUE,
103                condition_span,
104                BuiltinWhileTrue { suggestion: condition_span, replace },
105            );
106        }
107    }
108}
109
110#[doc =
r" The `non_shorthand_field_patterns` lint detects using `Struct { x: x }`"]
#[doc = r" instead of `Struct { x }` in a pattern."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" struct Point {"]
#[doc = r"     x: i32,"]
#[doc = r"     y: i32,"]
#[doc = r" }"]
#[doc = r""]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     let p = Point {"]
#[doc = r"         x: 5,"]
#[doc = r"         y: 5,"]
#[doc = r"     };"]
#[doc = r""]
#[doc = r"     match p {"]
#[doc = r"         Point { x: x, y: y } => (),"]
#[doc = r"     }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The preferred style is to avoid the repetition of specifying both the"]
#[doc = r" field name and the binding name if both identifiers are the same."]
static NON_SHORTHAND_FIELD_PATTERNS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NON_SHORTHAND_FIELD_PATTERNS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "using `Struct { x: x }` instead of `Struct { x }` in a pattern",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
111    /// The `non_shorthand_field_patterns` lint detects using `Struct { x: x }`
112    /// instead of `Struct { x }` in a pattern.
113    ///
114    /// ### Example
115    ///
116    /// ```rust
117    /// struct Point {
118    ///     x: i32,
119    ///     y: i32,
120    /// }
121    ///
122    ///
123    /// fn main() {
124    ///     let p = Point {
125    ///         x: 5,
126    ///         y: 5,
127    ///     };
128    ///
129    ///     match p {
130    ///         Point { x: x, y: y } => (),
131    ///     }
132    /// }
133    /// ```
134    ///
135    /// {{produces}}
136    ///
137    /// ### Explanation
138    ///
139    /// The preferred style is to avoid the repetition of specifying both the
140    /// field name and the binding name if both identifiers are the same.
141    NON_SHORTHAND_FIELD_PATTERNS,
142    Warn,
143    "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
144}
145
146pub struct NonShorthandFieldPatterns;
#[automatically_derived]
impl ::core::marker::Copy for NonShorthandFieldPatterns { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NonShorthandFieldPatterns { }
#[automatically_derived]
impl ::core::clone::Clone for NonShorthandFieldPatterns {
    #[inline]
    fn clone(&self) -> NonShorthandFieldPatterns { *self }
}
impl ::rustc_lint_defs::LintPass for NonShorthandFieldPatterns {
    fn name(&self) -> &'static str { "NonShorthandFieldPatterns" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_SHORTHAND_FIELD_PATTERNS]))
    }
}
impl NonShorthandFieldPatterns {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_SHORTHAND_FIELD_PATTERNS]))
    }
}declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
147
148impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns {
149    fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
150        // The result shouldn't be tainted, otherwise it will cause ICE.
151        if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind
152            && cx.typeck_results().tainted_by_errors.is_none()
153        {
154            let variant = cx
155                .typeck_results()
156                .pat_ty(pat)
157                .ty_adt_def()
158                .expect("struct pattern type is not an ADT")
159                .variant_of_res(cx.qpath_res(qpath, pat.hir_id));
160            for fieldpat in field_pats {
161                if fieldpat.is_shorthand {
162                    continue;
163                }
164                if fieldpat.span.from_expansion() {
165                    // Don't lint if this is a macro expansion: macro authors
166                    // shouldn't have to worry about this kind of style issue
167                    // (Issue #49588)
168                    continue;
169                }
170                if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
171                    if cx.tcx.find_field_index(ident, variant)
172                        == Some(cx.typeck_results().field_index(fieldpat.hir_id))
173                    {
174                        cx.emit_span_lint(
175                            NON_SHORTHAND_FIELD_PATTERNS,
176                            fieldpat.span,
177                            BuiltinNonShorthandFieldPatterns {
178                                ident,
179                                suggestion: fieldpat.span,
180                                prefix: binding_annot.prefix_str(),
181                            },
182                        );
183                    }
184                }
185            }
186        }
187    }
188}
189
190#[doc = r" The `unsafe_code` lint catches usage of `unsafe` code and other"]
#[doc = r" potentially unsound constructs like `no_mangle`, `export_name`,"]
#[doc = r" and `link_section`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unsafe_code)]"]
#[doc = r" fn main() {"]
#[doc = r"     unsafe {"]
#[doc = r""]
#[doc = r"     }"]
#[doc = r" }"]
#[doc = r""]
#[doc = r" #[no_mangle]"]
#[doc = r" fn func_0() { }"]
#[doc = r""]
#[doc = r#" #[export_name = "exported_symbol_name"]"#]
#[doc = r" pub fn name_in_rust() { }"]
#[doc = r""]
#[doc = r" #[no_mangle]"]
#[doc = r#" #[link_section = ".example_section"]"#]
#[doc = r" pub static VAR1: u32 = 1;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This lint is intended to restrict the usage of `unsafe` blocks and other"]
#[doc =
r" constructs (including, but not limited to `no_mangle`, `link_section`"]
#[doc =
r" and `export_name` attributes) wrong usage of which causes undefined"]
#[doc = r" behavior."]
static UNSAFE_CODE: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNSAFE_CODE",
            default_level: ::rustc_lint_defs::Allow,
            desc: "usage of `unsafe` code and other potentially unsound constructs",
            is_externally_loaded: false,
            eval_always: true,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
191    /// The `unsafe_code` lint catches usage of `unsafe` code and other
192    /// potentially unsound constructs like `no_mangle`, `export_name`,
193    /// and `link_section`.
194    ///
195    /// ### Example
196    ///
197    /// ```rust,compile_fail
198    /// #![deny(unsafe_code)]
199    /// fn main() {
200    ///     unsafe {
201    ///
202    ///     }
203    /// }
204    ///
205    /// #[no_mangle]
206    /// fn func_0() { }
207    ///
208    /// #[export_name = "exported_symbol_name"]
209    /// pub fn name_in_rust() { }
210    ///
211    /// #[no_mangle]
212    /// #[link_section = ".example_section"]
213    /// pub static VAR1: u32 = 1;
214    /// ```
215    ///
216    /// {{produces}}
217    ///
218    /// ### Explanation
219    ///
220    /// This lint is intended to restrict the usage of `unsafe` blocks and other
221    /// constructs (including, but not limited to `no_mangle`, `link_section`
222    /// and `export_name` attributes) wrong usage of which causes undefined
223    /// behavior.
224    UNSAFE_CODE,
225    Allow,
226    "usage of `unsafe` code and other potentially unsound constructs",
227    @eval_always = true
228}
229
230pub struct UnsafeCode;
#[automatically_derived]
impl ::core::marker::Copy for UnsafeCode { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnsafeCode { }
#[automatically_derived]
impl ::core::clone::Clone for UnsafeCode {
    #[inline]
    fn clone(&self) -> UnsafeCode { *self }
}
impl ::rustc_lint_defs::LintPass for UnsafeCode {
    fn name(&self) -> &'static str { "UnsafeCode" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNSAFE_CODE]))
    }
}
impl UnsafeCode {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNSAFE_CODE]))
    }
}declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
231
232impl UnsafeCode {
233    fn report_unsafe(
234        &self,
235        cx: &EarlyContext<'_>,
236        span: Span,
237        decorate: impl for<'a> Diagnostic<'a, ()>,
238    ) {
239        // This comes from a macro that has `#[allow_internal_unsafe]`.
240        if span.allows_unsafe() {
241            return;
242        }
243
244        cx.emit_span_lint(UNSAFE_CODE, span, decorate);
245    }
246}
247
248impl EarlyLintPass for UnsafeCode {
249    #[inline]
250    fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
251        if let ast::ExprKind::Block(ref blk, _) = e.kind {
252            // Don't warn about generated blocks; that'll just pollute the output.
253            if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
254                self.report_unsafe(cx, blk.span, BuiltinUnsafe::UnsafeBlock);
255            }
256        }
257    }
258
259    fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
260        match it.kind {
261            ast::ItemKind::Trait(box ast::Trait { safety: ast::Safety::Unsafe(_), .. }) => {
262                self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait);
263            }
264
265            ast::ItemKind::Impl(ast::Impl {
266                of_trait: Some(box ast::TraitImplHeader { safety: ast::Safety::Unsafe(_), .. }),
267                ..
268            }) => {
269                self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl);
270            }
271
272            ast::ItemKind::Fn(..) => {
273                if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
274                    self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleFn);
275                }
276
277                if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
278                    self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameFn);
279                }
280
281                if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
282                    self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionFn);
283                }
284            }
285
286            ast::ItemKind::Static(..) => {
287                if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
288                    self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleStatic);
289                }
290
291                if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
292                    self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameStatic);
293                }
294
295                if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
296                    self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionStatic);
297                }
298            }
299
300            ast::ItemKind::GlobalAsm(..) => {
301                self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm);
302            }
303
304            ast::ItemKind::ForeignMod(ForeignMod { safety, .. }) => {
305                if let Safety::Unsafe(_) = safety {
306                    self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeExternBlock);
307                }
308            }
309
310            ast::ItemKind::MacroDef(..) => {
311                if let Some(hir::Attribute::Parsed(AttributeKind::AllowInternalUnsafe(span))) =
312                    AttributeParser::parse_limited(
313                        cx.builder.sess(),
314                        &it.attrs,
315                        &[sym::allow_internal_unsafe],
316                    )
317                {
318                    self.report_unsafe(cx, span, BuiltinUnsafe::AllowInternalUnsafe);
319                }
320            }
321
322            _ => {}
323        }
324    }
325
326    fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
327        if let ast::AssocItemKind::Fn(..) = it.kind {
328            if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
329                self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleMethod);
330            }
331            if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
332                self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameMethod);
333            }
334        }
335    }
336
337    fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) {
338        if let FnKind::Fn(
339            ctxt,
340            _,
341            ast::Fn {
342                sig: ast::FnSig { header: ast::FnHeader { safety: ast::Safety::Unsafe(_), .. }, .. },
343                body,
344                ..
345            },
346        ) = fk
347        {
348            let decorator = match ctxt {
349                FnCtxt::Foreign => return,
350                FnCtxt::Free => BuiltinUnsafe::DeclUnsafeFn,
351                FnCtxt::Assoc(_) if body.is_none() => BuiltinUnsafe::DeclUnsafeMethod,
352                FnCtxt::Assoc(_) => BuiltinUnsafe::ImplUnsafeMethod,
353            };
354            self.report_unsafe(cx, span, decorator);
355        }
356    }
357}
358
359#[doc =
r" The `missing_docs` lint detects missing documentation for public items."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_docs)]"]
#[doc = r" pub fn foo() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This lint is intended to ensure that a library is well-documented."]
#[doc =
r" Items without documentation can be difficult for users to understand"]
#[doc = r" how to use properly."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it can be noisy, and not all"#]
#[doc = r" projects may want to enforce everything to be documented."]
pub static MISSING_DOCS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "MISSING_DOCS",
            default_level: ::rustc_lint_defs::Allow,
            desc: "detects missing documentation for public members",
            is_externally_loaded: false,
            report_in_external_macro: true,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
360    /// The `missing_docs` lint detects missing documentation for public items.
361    ///
362    /// ### Example
363    ///
364    /// ```rust,compile_fail
365    /// #![deny(missing_docs)]
366    /// pub fn foo() {}
367    /// ```
368    ///
369    /// {{produces}}
370    ///
371    /// ### Explanation
372    ///
373    /// This lint is intended to ensure that a library is well-documented.
374    /// Items without documentation can be difficult for users to understand
375    /// how to use properly.
376    ///
377    /// This lint is "allow" by default because it can be noisy, and not all
378    /// projects may want to enforce everything to be documented.
379    pub MISSING_DOCS,
380    Allow,
381    "detects missing documentation for public members",
382    report_in_external_macro
383}
384
385#[derive(#[automatically_derived]
impl ::core::default::Default for MissingDoc {
    #[inline]
    fn default() -> MissingDoc { MissingDoc {} }
}Default)]
386pub struct MissingDoc;
387
388impl ::rustc_lint_defs::LintPass for MissingDoc {
    fn name(&self) -> &'static str { "MissingDoc" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_DOCS]))
    }
}
impl MissingDoc {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_DOCS]))
    }
}impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
389
390fn has_doc(attr: &hir::Attribute) -> bool {
391    if #[allow(non_exhaustive_omitted_patterns)] match attr {
    hir::Attribute::Parsed(AttributeKind::DocComment { .. }) => true,
    _ => false,
}matches!(attr, hir::Attribute::Parsed(AttributeKind::DocComment { .. })) {
392        return true;
393    }
394
395    if let hir::Attribute::Parsed(AttributeKind::Doc(d)) = attr
396        && #[allow(non_exhaustive_omitted_patterns)] match d.as_ref() {
    DocAttribute { hidden: Some(..), .. } => true,
    _ => false,
}matches!(d.as_ref(), DocAttribute { hidden: Some(..), .. })
397    {
398        return true;
399    }
400
401    false
402}
403
404impl MissingDoc {
405    fn check_missing_docs_attrs(
406        &self,
407        cx: &LateContext<'_>,
408        def_id: LocalDefId,
409        article: &'static str,
410        desc: &'static str,
411    ) {
412        // Only check publicly-visible items, using the result from the privacy pass.
413        // It's an option so the crate root can also use this function (it doesn't
414        // have a `NodeId`).
415        if def_id != CRATE_DEF_ID && !cx.effective_visibilities.is_exported(def_id) {
416            return;
417        }
418
419        let attrs = cx.tcx.hir_attrs(cx.tcx.local_def_id_to_hir_id(def_id));
420        let has_doc = attrs.iter().any(has_doc);
421        if !has_doc {
422            cx.emit_span_lint(
423                MISSING_DOCS,
424                cx.tcx.def_span(def_id),
425                BuiltinMissingDoc { article, desc },
426            );
427        }
428    }
429}
430
431impl<'tcx> LateLintPass<'tcx> for MissingDoc {
432    fn check_crate(&mut self, cx: &LateContext<'_>) {
433        self.check_missing_docs_attrs(cx, CRATE_DEF_ID, "the", "crate");
434    }
435
436    fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
437        // Previously the Impl and Use types have been excluded from missing docs,
438        // so we will continue to exclude them for compatibility.
439        //
440        // The documentation on `ExternCrate` is not used at the moment so no need to warn for it.
441        if let hir::ItemKind::Impl(..) | hir::ItemKind::Use(..) | hir::ItemKind::ExternCrate(..) =
442            it.kind
443        {
444            return;
445        }
446
447        let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id());
448        self.check_missing_docs_attrs(cx, it.owner_id.def_id, article, desc);
449    }
450
451    fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) {
452        let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id());
453
454        self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, article, desc);
455    }
456
457    fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
458        let container = cx.tcx.associated_item(impl_item.owner_id.def_id).container;
459
460        match container {
461            // If the method is an impl for a trait, don't doc.
462            AssocContainer::TraitImpl(_) => return,
463            AssocContainer::Trait => {}
464            // If the method is an impl for an item with docs_hidden, don't doc.
465            AssocContainer::InherentImpl => {
466                let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id());
467                let impl_ty = cx.tcx.type_of(parent).instantiate_identity();
468                let outerdef = match impl_ty.kind() {
469                    ty::Adt(def, _) => Some(def.did()),
470                    ty::Foreign(def_id) => Some(*def_id),
471                    _ => None,
472                };
473                let is_hidden = match outerdef {
474                    Some(id) => cx.tcx.is_doc_hidden(id),
475                    None => false,
476                };
477                if is_hidden {
478                    return;
479                }
480            }
481        }
482
483        let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id());
484        self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, article, desc);
485    }
486
487    fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) {
488        let (article, desc) = cx.tcx.article_and_description(foreign_item.owner_id.to_def_id());
489        self.check_missing_docs_attrs(cx, foreign_item.owner_id.def_id, article, desc);
490    }
491
492    fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) {
493        if !sf.is_positional() {
494            self.check_missing_docs_attrs(cx, sf.def_id, "a", "struct field")
495        }
496    }
497
498    fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) {
499        self.check_missing_docs_attrs(cx, v.def_id, "a", "variant");
500    }
501}
502
503#[doc =
r" The `missing_copy_implementations` lint detects potentially-forgotten"]
#[doc = r" implementations of [`Copy`] for public types."]
#[doc = r""]
#[doc = r" [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_copy_implementations)]"]
#[doc = r" pub struct Foo {"]
#[doc = r"     pub field: i32"]
#[doc = r" }"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Historically (before 1.0), types were automatically marked as `Copy`"]
#[doc =
r" if possible. This was changed so that it required an explicit opt-in"]
#[doc =
r" by implementing the `Copy` trait. As part of this change, a lint was"]
#[doc = r" added to alert if a copyable type was not marked `Copy`."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because this code isn't bad; it is"#]
#[doc =
r" common to write newtypes like this specifically so that a `Copy` type"]
#[doc =
r" is no longer `Copy`. `Copy` types can result in unintended copies of"]
#[doc = r" large data which can impact performance."]
pub static MISSING_COPY_IMPLEMENTATIONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "MISSING_COPY_IMPLEMENTATIONS",
            default_level: ::rustc_lint_defs::Allow,
            desc: "detects potentially-forgotten implementations of `Copy`",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
504    /// The `missing_copy_implementations` lint detects potentially-forgotten
505    /// implementations of [`Copy`] for public types.
506    ///
507    /// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html
508    ///
509    /// ### Example
510    ///
511    /// ```rust,compile_fail
512    /// #![deny(missing_copy_implementations)]
513    /// pub struct Foo {
514    ///     pub field: i32
515    /// }
516    /// # fn main() {}
517    /// ```
518    ///
519    /// {{produces}}
520    ///
521    /// ### Explanation
522    ///
523    /// Historically (before 1.0), types were automatically marked as `Copy`
524    /// if possible. This was changed so that it required an explicit opt-in
525    /// by implementing the `Copy` trait. As part of this change, a lint was
526    /// added to alert if a copyable type was not marked `Copy`.
527    ///
528    /// This lint is "allow" by default because this code isn't bad; it is
529    /// common to write newtypes like this specifically so that a `Copy` type
530    /// is no longer `Copy`. `Copy` types can result in unintended copies of
531    /// large data which can impact performance.
532    pub MISSING_COPY_IMPLEMENTATIONS,
533    Allow,
534    "detects potentially-forgotten implementations of `Copy`"
535}
536
537pub struct MissingCopyImplementations;
#[automatically_derived]
impl ::core::marker::Copy for MissingCopyImplementations { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MissingCopyImplementations { }
#[automatically_derived]
impl ::core::clone::Clone for MissingCopyImplementations {
    #[inline]
    fn clone(&self) -> MissingCopyImplementations { *self }
}
impl ::rustc_lint_defs::LintPass for MissingCopyImplementations {
    fn name(&self) -> &'static str { "MissingCopyImplementations" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_COPY_IMPLEMENTATIONS]))
    }
}
impl MissingCopyImplementations {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_COPY_IMPLEMENTATIONS]))
    }
}declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
538
539impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
540    fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
541        if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
542            return;
543        }
544        let (def, ty) = match item.kind {
545            hir::ItemKind::Struct(_, generics, _) => {
546                if !generics.params.is_empty() {
547                    return;
548                }
549                let def = cx.tcx.adt_def(item.owner_id);
550                (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
551            }
552            hir::ItemKind::Union(_, generics, _) => {
553                if !generics.params.is_empty() {
554                    return;
555                }
556                let def = cx.tcx.adt_def(item.owner_id);
557                (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
558            }
559            hir::ItemKind::Enum(_, generics, _) => {
560                if !generics.params.is_empty() {
561                    return;
562                }
563                let def = cx.tcx.adt_def(item.owner_id);
564                (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
565            }
566            _ => return,
567        };
568        if def.has_dtor(cx.tcx) {
569            return;
570        }
571
572        // If the type contains a raw pointer, it may represent something like a handle,
573        // and recommending Copy might be a bad idea.
574        for field in def.all_fields() {
575            let did = field.did;
576            if cx.tcx.type_of(did).instantiate_identity().is_raw_ptr() {
577                return;
578            }
579        }
580        if cx.type_is_copy_modulo_regions(ty) {
581            return;
582        }
583        if type_implements_negative_copy_modulo_regions(cx.tcx, ty, cx.typing_env()) {
584            return;
585        }
586        if def.is_variant_list_non_exhaustive()
587            || def.variants().iter().any(|variant| variant.is_field_list_non_exhaustive())
588        {
589            return;
590        }
591
592        // We shouldn't recommend implementing `Copy` on stateful things,
593        // such as iterators.
594        if let Some(iter_trait) = cx.tcx.get_diagnostic_item(sym::Iterator)
595            && cx
596                .tcx
597                .infer_ctxt()
598                .build(cx.typing_mode())
599                .type_implements_trait(iter_trait, [ty], cx.param_env)
600                .must_apply_modulo_regions()
601        {
602            return;
603        }
604
605        // Default value of clippy::trivially_copy_pass_by_ref
606        const MAX_SIZE: u64 = 256;
607
608        if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes()) {
609            if size > MAX_SIZE {
610                return;
611            }
612        }
613
614        if type_allowed_to_implement_copy(
615            cx.tcx,
616            cx.param_env,
617            ty,
618            traits::ObligationCause::misc(item.span, item.owner_id.def_id),
619            hir::Safety::Safe,
620        )
621        .is_ok()
622        {
623            cx.emit_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, BuiltinMissingCopyImpl);
624        }
625    }
626}
627
628/// Check whether a `ty` has a negative `Copy` implementation, ignoring outlives constraints.
629fn type_implements_negative_copy_modulo_regions<'tcx>(
630    tcx: TyCtxt<'tcx>,
631    ty: Ty<'tcx>,
632    typing_env: ty::TypingEnv<'tcx>,
633) -> bool {
634    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
635    let trait_ref =
636        ty::TraitRef::new(tcx, tcx.require_lang_item(hir::LangItem::Copy, DUMMY_SP), [ty]);
637    let pred = ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Negative };
638    let obligation = traits::Obligation {
639        cause: traits::ObligationCause::dummy(),
640        param_env,
641        recursion_depth: 0,
642        predicate: pred.upcast(tcx),
643    };
644    infcx.predicate_must_hold_modulo_regions(&obligation)
645}
646
647#[doc = r" The `missing_debug_implementations` lint detects missing"]
#[doc = r" implementations of [`fmt::Debug`] for public types."]
#[doc = r""]
#[doc =
r" [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_debug_implementations)]"]
#[doc = r" pub struct Foo;"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Having a `Debug` implementation on all types can assist with"]
#[doc =
r" debugging, as it provides a convenient way to format and display a"]
#[doc = r" value. Using the `#[derive(Debug)]` attribute will automatically"]
#[doc =
r" generate a typical implementation, or a custom implementation can be"]
#[doc = r" added by manually implementing the `Debug` trait."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because adding `Debug` to all types can"#]
#[doc =
r" have a negative impact on compile time and code size. It also requires"]
#[doc =
r" boilerplate to be added to every type, which can be an impediment."]
static MISSING_DEBUG_IMPLEMENTATIONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "MISSING_DEBUG_IMPLEMENTATIONS",
            default_level: ::rustc_lint_defs::Allow,
            desc: "detects missing implementations of Debug",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
648    /// The `missing_debug_implementations` lint detects missing
649    /// implementations of [`fmt::Debug`] for public types.
650    ///
651    /// [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
652    ///
653    /// ### Example
654    ///
655    /// ```rust,compile_fail
656    /// #![deny(missing_debug_implementations)]
657    /// pub struct Foo;
658    /// # fn main() {}
659    /// ```
660    ///
661    /// {{produces}}
662    ///
663    /// ### Explanation
664    ///
665    /// Having a `Debug` implementation on all types can assist with
666    /// debugging, as it provides a convenient way to format and display a
667    /// value. Using the `#[derive(Debug)]` attribute will automatically
668    /// generate a typical implementation, or a custom implementation can be
669    /// added by manually implementing the `Debug` trait.
670    ///
671    /// This lint is "allow" by default because adding `Debug` to all types can
672    /// have a negative impact on compile time and code size. It also requires
673    /// boilerplate to be added to every type, which can be an impediment.
674    MISSING_DEBUG_IMPLEMENTATIONS,
675    Allow,
676    "detects missing implementations of Debug"
677}
678
679#[derive(#[automatically_derived]
impl ::core::default::Default for MissingDebugImplementations {
    #[inline]
    fn default() -> MissingDebugImplementations {
        MissingDebugImplementations {}
    }
}Default)]
680pub(crate) struct MissingDebugImplementations;
681
682impl ::rustc_lint_defs::LintPass for MissingDebugImplementations {
    fn name(&self) -> &'static str { "MissingDebugImplementations" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_DEBUG_IMPLEMENTATIONS]))
    }
}
impl MissingDebugImplementations {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_DEBUG_IMPLEMENTATIONS]))
    }
}impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
683
684impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations {
685    fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
686        if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
687            return;
688        }
689
690        match item.kind {
691            hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
692            _ => return,
693        }
694
695        // Avoid listing trait impls if the trait is allowed.
696        let LevelAndSource { level, .. } =
697            cx.tcx.lint_level_at_node(MISSING_DEBUG_IMPLEMENTATIONS, item.hir_id());
698        if level == Level::Allow {
699            return;
700        }
701
702        let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { return };
703
704        let has_impl = cx
705            .tcx
706            .non_blanket_impls_for_ty(debug, cx.tcx.type_of(item.owner_id).instantiate_identity())
707            .next()
708            .is_some();
709        if !has_impl {
710            cx.emit_span_lint(
711                MISSING_DEBUG_IMPLEMENTATIONS,
712                item.span,
713                BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug },
714            );
715        }
716    }
717}
718
719#[doc =
r" The `anonymous_parameters` lint detects anonymous parameters in trait"]
#[doc = r" definitions."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(anonymous_parameters)]"]
#[doc = r" // edition 2015"]
#[doc = r" pub trait Foo {"]
#[doc = r"     fn foo(usize);"]
#[doc = r" }"]
#[doc = r" fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This syntax is mostly a historical accident, and can be worked around"]
#[doc =
r" quite easily by adding an `_` pattern or a descriptive identifier:"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" trait Foo {"]
#[doc = r"     fn foo(_: usize);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" This syntax is now a hard error in the 2018 edition. In the 2015"]
#[doc = r#" edition, this lint is "warn" by default. This lint"#]
#[doc = r" enables the [`cargo fix`] tool with the `--edition` flag to"]
#[doc =
r" automatically transition old code from the 2015 edition to 2018. The"]
#[doc = r" tool will run this lint and automatically apply the"]
#[doc = r" suggested fix from the compiler (which is to add `_` to each"]
#[doc =
r" parameter). This provides a completely automated way to update old"]
#[doc = r" code for a new edition. See [issue #41686] for more details."]
#[doc = r""]
#[doc = r" [issue #41686]: https://github.com/rust-lang/rust/issues/41686"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static ANONYMOUS_PARAMETERS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "ANONYMOUS_PARAMETERS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "detects anonymous parameters",
            is_externally_loaded: false,
            future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
                    reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
                            edition: rustc_span::edition::Edition::Edition2018,
                            page_slug: "trait-fn-parameters",
                        }),
                    ..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
                }),
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
720    /// The `anonymous_parameters` lint detects anonymous parameters in trait
721    /// definitions.
722    ///
723    /// ### Example
724    ///
725    /// ```rust,edition2015,compile_fail
726    /// #![deny(anonymous_parameters)]
727    /// // edition 2015
728    /// pub trait Foo {
729    ///     fn foo(usize);
730    /// }
731    /// fn main() {}
732    /// ```
733    ///
734    /// {{produces}}
735    ///
736    /// ### Explanation
737    ///
738    /// This syntax is mostly a historical accident, and can be worked around
739    /// quite easily by adding an `_` pattern or a descriptive identifier:
740    ///
741    /// ```rust
742    /// trait Foo {
743    ///     fn foo(_: usize);
744    /// }
745    /// ```
746    ///
747    /// This syntax is now a hard error in the 2018 edition. In the 2015
748    /// edition, this lint is "warn" by default. This lint
749    /// enables the [`cargo fix`] tool with the `--edition` flag to
750    /// automatically transition old code from the 2015 edition to 2018. The
751    /// tool will run this lint and automatically apply the
752    /// suggested fix from the compiler (which is to add `_` to each
753    /// parameter). This provides a completely automated way to update old
754    /// code for a new edition. See [issue #41686] for more details.
755    ///
756    /// [issue #41686]: https://github.com/rust-lang/rust/issues/41686
757    /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
758    pub ANONYMOUS_PARAMETERS,
759    Warn,
760    "detects anonymous parameters",
761    @future_incompatible = FutureIncompatibleInfo {
762        reason: fcw!(EditionError 2018 "trait-fn-parameters"),
763    };
764}
765
766#[doc = r" Checks for use of anonymous parameters (RFC 1685)."]
pub struct AnonymousParameters;
#[automatically_derived]
impl ::core::marker::Copy for AnonymousParameters { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AnonymousParameters { }
#[automatically_derived]
impl ::core::clone::Clone for AnonymousParameters {
    #[inline]
    fn clone(&self) -> AnonymousParameters { *self }
}
impl ::rustc_lint_defs::LintPass for AnonymousParameters {
    fn name(&self) -> &'static str { "AnonymousParameters" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [ANONYMOUS_PARAMETERS]))
    }
}
impl AnonymousParameters {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [ANONYMOUS_PARAMETERS]))
    }
}declare_lint_pass!(
767    /// Checks for use of anonymous parameters (RFC 1685).
768    AnonymousParameters => [ANONYMOUS_PARAMETERS]
769);
770
771impl EarlyLintPass for AnonymousParameters {
772    fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
773        if cx.sess().edition() != Edition::Edition2015 {
774            // This is a hard error in future editions; avoid linting and erroring
775            return;
776        }
777        if let ast::AssocItemKind::Fn(box Fn { ref sig, .. }) = it.kind {
778            for arg in sig.decl.inputs.iter() {
779                if let ast::PatKind::Missing = arg.pat.kind {
780                    let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span);
781
782                    let (ty_snip, appl) = if let Ok(ref snip) = ty_snip {
783                        (snip.as_str(), Applicability::MachineApplicable)
784                    } else {
785                        ("<type>", Applicability::HasPlaceholders)
786                    };
787                    cx.emit_span_lint(
788                        ANONYMOUS_PARAMETERS,
789                        arg.pat.span,
790                        BuiltinAnonymousParams { suggestion: (arg.pat.span, appl), ty_snip },
791                    );
792                }
793            }
794        }
795    }
796}
797
798fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) {
799    use rustc_ast::token::CommentKind;
800
801    let mut attrs = attrs.iter().peekable();
802
803    // Accumulate a single span for sugared doc comments.
804    let mut sugared_span: Option<Span> = None;
805
806    while let Some(attr) = attrs.next() {
807        let (is_doc_comment, is_doc_attribute) = match &attr.kind {
808            AttrKind::DocComment(..) => (true, false),
809            AttrKind::Normal(normal) if normal.item.path == sym::doc => (true, true),
810            _ => (false, false),
811        };
812        if is_doc_comment {
813            sugared_span =
814                Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi())));
815        }
816
817        if !is_doc_attribute && attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) {
818            continue;
819        }
820
821        let span = sugared_span.take().unwrap_or(attr.span);
822
823        if is_doc_comment || is_doc_attribute {
824            let sub = match attr.kind {
825                AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => {
826                    BuiltinUnusedDocCommentSub::PlainHelp
827                }
828                AttrKind::DocComment(CommentKind::Block, _) => {
829                    BuiltinUnusedDocCommentSub::BlockHelp
830                }
831            };
832            cx.emit_span_lint(
833                UNUSED_DOC_COMMENTS,
834                span,
835                BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub },
836            );
837        }
838    }
839}
840
841impl EarlyLintPass for UnusedDocComment {
842    fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
843        let kind = match stmt.kind {
844            ast::StmtKind::Let(..) => "statements",
845            // Disabled pending discussion in #78306
846            ast::StmtKind::Item(..) => return,
847            // expressions will be reported by `check_expr`.
848            ast::StmtKind::Empty
849            | ast::StmtKind::Semi(_)
850            | ast::StmtKind::Expr(_)
851            | ast::StmtKind::MacCall(_) => return,
852        };
853
854        warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs());
855    }
856
857    fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
858        if let Some(body) = &arm.body {
859            let arm_span = arm.pat.span.with_hi(body.span.hi());
860            warn_if_doc(cx, arm_span, "match arms", &arm.attrs);
861        }
862    }
863
864    fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
865        if let ast::PatKind::Struct(_, _, fields, _) = &pat.kind {
866            for field in fields {
867                warn_if_doc(cx, field.span, "pattern fields", &field.attrs);
868            }
869        }
870    }
871
872    fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
873        warn_if_doc(cx, expr.span, "expressions", &expr.attrs);
874
875        if let ExprKind::Struct(s) = &expr.kind {
876            for field in &s.fields {
877                warn_if_doc(cx, field.span, "expression fields", &field.attrs);
878            }
879        }
880    }
881
882    fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
883        warn_if_doc(cx, param.ident.span, "generic parameters", &param.attrs);
884    }
885
886    fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
887        warn_if_doc(cx, block.span, "blocks", block.attrs());
888    }
889
890    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
891        if let ast::ItemKind::ForeignMod(_) = item.kind {
892            warn_if_doc(cx, item.span, "extern blocks", &item.attrs);
893        }
894    }
895}
896
897#[doc =
r" The `no_mangle_const_items` lint detects any `const` items with the"]
#[doc = r" [`no_mangle` attribute]."]
#[doc = r""]
#[doc =
r" [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail,edition2021"]
#[doc = r" #[no_mangle]"]
#[doc = r" const FOO: i32 = 5;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Constants do not have their symbols exported, and therefore, this"]
#[doc = r" probably means you meant to use a [`static`], not a [`const`]."]
#[doc = r""]
#[doc =
r" [`static`]: https://doc.rust-lang.org/reference/items/static-items.html"]
#[doc =
r" [`const`]: https://doc.rust-lang.org/reference/items/constant-items.html"]
static NO_MANGLE_CONST_ITEMS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NO_MANGLE_CONST_ITEMS",
            default_level: ::rustc_lint_defs::Deny,
            desc: "const items will not have their symbols exported",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
898    /// The `no_mangle_const_items` lint detects any `const` items with the
899    /// [`no_mangle` attribute].
900    ///
901    /// [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
902    ///
903    /// ### Example
904    ///
905    /// ```rust,compile_fail,edition2021
906    /// #[no_mangle]
907    /// const FOO: i32 = 5;
908    /// ```
909    ///
910    /// {{produces}}
911    ///
912    /// ### Explanation
913    ///
914    /// Constants do not have their symbols exported, and therefore, this
915    /// probably means you meant to use a [`static`], not a [`const`].
916    ///
917    /// [`static`]: https://doc.rust-lang.org/reference/items/static-items.html
918    /// [`const`]: https://doc.rust-lang.org/reference/items/constant-items.html
919    NO_MANGLE_CONST_ITEMS,
920    Deny,
921    "const items will not have their symbols exported"
922}
923
924#[doc =
r" The `no_mangle_generic_items` lint detects generic items that must be"]
#[doc = r" mangled."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #[unsafe(no_mangle)]"]
#[doc = r" fn foo<T>(t: T) {}"]
#[doc = r""]
#[doc = r#" #[unsafe(export_name = "bar")]"#]
#[doc = r" fn bar<T>(t: T) {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" A function with generics must have its symbol mangled to accommodate"]
#[doc =
r" the generic parameter. The [`no_mangle`] and [`export_name`] attributes"]
#[doc = r" have no effect in this situation, and should be removed."]
#[doc = r""]
#[doc =
r" [`no_mangle`]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"]
#[doc =
r" [`export_name`]: https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute"]
static NO_MANGLE_GENERIC_ITEMS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NO_MANGLE_GENERIC_ITEMS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "generic items must be mangled",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
925    /// The `no_mangle_generic_items` lint detects generic items that must be
926    /// mangled.
927    ///
928    /// ### Example
929    ///
930    /// ```rust
931    /// #[unsafe(no_mangle)]
932    /// fn foo<T>(t: T) {}
933    ///
934    /// #[unsafe(export_name = "bar")]
935    /// fn bar<T>(t: T) {}
936    /// ```
937    ///
938    /// {{produces}}
939    ///
940    /// ### Explanation
941    ///
942    /// A function with generics must have its symbol mangled to accommodate
943    /// the generic parameter. The [`no_mangle`] and [`export_name`] attributes
944    /// have no effect in this situation, and should be removed.
945    ///
946    /// [`no_mangle`]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
947    /// [`export_name`]: https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute
948    NO_MANGLE_GENERIC_ITEMS,
949    Warn,
950    "generic items must be mangled"
951}
952
953pub struct InvalidNoMangleItems;
#[automatically_derived]
impl ::core::marker::Copy for InvalidNoMangleItems { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidNoMangleItems { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidNoMangleItems {
    #[inline]
    fn clone(&self) -> InvalidNoMangleItems { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidNoMangleItems {
    fn name(&self) -> &'static str { "InvalidNoMangleItems" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]))
    }
}
impl InvalidNoMangleItems {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]))
    }
}declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
954
955impl InvalidNoMangleItems {
956    fn check_no_mangle_on_generic_fn(
957        &self,
958        cx: &LateContext<'_>,
959        attr_span: Span,
960        def_id: LocalDefId,
961    ) {
962        let generics = cx.tcx.generics_of(def_id);
963        if generics.requires_monomorphization(cx.tcx) {
964            cx.emit_span_lint(
965                NO_MANGLE_GENERIC_ITEMS,
966                cx.tcx.def_span(def_id),
967                BuiltinNoMangleGeneric { suggestion: attr_span },
968            );
969        }
970    }
971}
972
973impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
974    fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
975        let attrs = cx.tcx.hir_attrs(it.hir_id());
976        match it.kind {
977            hir::ItemKind::Fn { .. } => {
978                if let Some(attr_span) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(ExportName { span, .. }) => {
                    break 'done Some(*span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, ExportName {span, ..} => *span)
979                    .or_else(|| {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(NoMangle(span)) => {
                    break 'done Some(*span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, NoMangle(span) => *span))
980                {
981                    self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
982                }
983            }
984            hir::ItemKind::Const(ident, generics, ..) => {
985                if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(NoMangle(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, NoMangle(..)) {
986                    let suggestion =
987                        if generics.params.is_empty() && generics.where_clause_span.is_empty() {
988                            // account for "pub const" (#45562)
989                            Some(it.span.until(ident.span))
990                        } else {
991                            None
992                        };
993
994                    // Const items do not refer to a particular location in memory, and therefore
995                    // don't have anything to attach a symbol to
996                    cx.emit_span_lint(
997                        NO_MANGLE_CONST_ITEMS,
998                        it.span,
999                        BuiltinConstNoMangle { suggestion },
1000                    );
1001                }
1002            }
1003            _ => {}
1004        }
1005    }
1006
1007    fn check_impl_item(&mut self, cx: &LateContext<'_>, it: &hir::ImplItem<'_>) {
1008        let attrs = cx.tcx.hir_attrs(it.hir_id());
1009        match it.kind {
1010            hir::ImplItemKind::Fn { .. } => {
1011                if let Some(attr_span) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(ExportName { span, .. }) => {
                    break 'done Some(*span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, ExportName {span, ..} => *span)
1012                    .or_else(|| {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(NoMangle(span)) => {
                    break 'done Some(*span);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, NoMangle(span) => *span))
1013                {
1014                    self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
1015                }
1016            }
1017            _ => {}
1018        }
1019    }
1020}
1021
1022#[doc =
r" The `mutable_transmutes` lint catches transmuting from `&T` to `&mut"]
#[doc = r" T` because it is [undefined behavior]."]
#[doc = r""]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" unsafe {"]
#[doc = r"     let y = std::mem::transmute::<&i32, &mut i32>(&5);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Certain assumptions are made about aliasing of data, and this transmute"]
#[doc =
r" violates those assumptions. Consider using [`UnsafeCell`] instead."]
#[doc = r""]
#[doc =
r" [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html"]
static MUTABLE_TRANSMUTES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "MUTABLE_TRANSMUTES",
            default_level: ::rustc_lint_defs::Deny,
            desc: "transmuting &T to &mut T is undefined behavior, even if the reference is unused",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1023    /// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut
1024    /// T` because it is [undefined behavior].
1025    ///
1026    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1027    ///
1028    /// ### Example
1029    ///
1030    /// ```rust,compile_fail
1031    /// unsafe {
1032    ///     let y = std::mem::transmute::<&i32, &mut i32>(&5);
1033    /// }
1034    /// ```
1035    ///
1036    /// {{produces}}
1037    ///
1038    /// ### Explanation
1039    ///
1040    /// Certain assumptions are made about aliasing of data, and this transmute
1041    /// violates those assumptions. Consider using [`UnsafeCell`] instead.
1042    ///
1043    /// [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
1044    MUTABLE_TRANSMUTES,
1045    Deny,
1046    "transmuting &T to &mut T is undefined behavior, even if the reference is unused"
1047}
1048
1049pub struct MutableTransmutes;
#[automatically_derived]
impl ::core::marker::Copy for MutableTransmutes { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MutableTransmutes { }
#[automatically_derived]
impl ::core::clone::Clone for MutableTransmutes {
    #[inline]
    fn clone(&self) -> MutableTransmutes { *self }
}
impl ::rustc_lint_defs::LintPass for MutableTransmutes {
    fn name(&self) -> &'static str { "MutableTransmutes" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MUTABLE_TRANSMUTES]))
    }
}
impl MutableTransmutes {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MUTABLE_TRANSMUTES]))
    }
}declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
1050
1051impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
1052    fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
1053        if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
1054            get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
1055        {
1056            if from_mutbl < to_mutbl {
1057                cx.emit_span_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
1058            }
1059        }
1060
1061        fn get_transmute_from_to<'tcx>(
1062            cx: &LateContext<'tcx>,
1063            expr: &hir::Expr<'_>,
1064        ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
1065            let hir::ExprKind::Path(ref qpath) = expr.kind else { return None };
1066            let def = cx.qpath_res(qpath, expr.hir_id);
1067            if let Res::Def(DefKind::Fn, did) = def {
1068                if !def_id_is_transmute(cx, did) {
1069                    return None;
1070                }
1071                let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
1072                let from = sig.inputs().skip_binder()[0];
1073                let to = sig.output().skip_binder();
1074                return Some((from, to));
1075            }
1076            None
1077        }
1078
1079        fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
1080            cx.tcx.is_intrinsic(def_id, sym::transmute)
1081        }
1082    }
1083}
1084
1085#[doc = r" The `unstable_features` lint detects uses of `#![feature]`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unstable_features)]"]
#[doc = r" #![feature(test)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" In larger nightly-based projects which"]
#[doc = r""]
#[doc =
r" * consist of a multitude of crates where a subset of crates has to compile on"]
#[doc =
r"   stable either unconditionally or depending on a `cfg` flag to for example"]
#[doc = r"   allow stable users to depend on them,"]
#[doc =
r" * don't use nightly for experimental features but for, e.g., unstable options only,"]
#[doc = r""]
#[doc = r" this lint may come in handy to enforce policies of these kinds."]
static UNSTABLE_FEATURES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNSTABLE_FEATURES",
            default_level: ::rustc_lint_defs::Allow,
            desc: "enabling unstable features",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1086    /// The `unstable_features` lint detects uses of `#![feature]`.
1087    ///
1088    /// ### Example
1089    ///
1090    /// ```rust,compile_fail
1091    /// #![deny(unstable_features)]
1092    /// #![feature(test)]
1093    /// ```
1094    ///
1095    /// {{produces}}
1096    ///
1097    /// ### Explanation
1098    ///
1099    /// In larger nightly-based projects which
1100    ///
1101    /// * consist of a multitude of crates where a subset of crates has to compile on
1102    ///   stable either unconditionally or depending on a `cfg` flag to for example
1103    ///   allow stable users to depend on them,
1104    /// * don't use nightly for experimental features but for, e.g., unstable options only,
1105    ///
1106    /// this lint may come in handy to enforce policies of these kinds.
1107    UNSTABLE_FEATURES,
1108    Allow,
1109    "enabling unstable features"
1110}
1111
1112#[doc = r" Forbids using the `#[feature(...)]` attribute"]
pub struct UnstableFeatures;
#[automatically_derived]
impl ::core::marker::Copy for UnstableFeatures { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnstableFeatures { }
#[automatically_derived]
impl ::core::clone::Clone for UnstableFeatures {
    #[inline]
    fn clone(&self) -> UnstableFeatures { *self }
}
impl ::rustc_lint_defs::LintPass for UnstableFeatures {
    fn name(&self) -> &'static str { "UnstableFeatures" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNSTABLE_FEATURES]))
    }
}
impl UnstableFeatures {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNSTABLE_FEATURES]))
    }
}declare_lint_pass!(
1113    /// Forbids using the `#[feature(...)]` attribute
1114    UnstableFeatures => [UNSTABLE_FEATURES]
1115);
1116
1117impl<'tcx> LateLintPass<'tcx> for UnstableFeatures {
1118    fn check_attributes(&mut self, cx: &LateContext<'_>, attrs: &[hir::Attribute]) {
1119        if let Some(features) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Feature(features, _)) => {
                    break 'done Some(features);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Feature(features, _) => features) {
1120            for feature in features {
1121                cx.emit_span_lint(UNSTABLE_FEATURES, feature.span, BuiltinUnstableFeatures);
1122            }
1123        }
1124    }
1125}
1126
1127#[doc = r" The `ungated_async_fn_track_caller` lint warns when the"]
#[doc = r" `#[track_caller]` attribute is used on an async function"]
#[doc = r" without enabling the corresponding unstable feature flag."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #[track_caller]"]
#[doc = r" async fn foo() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The attribute must be used in conjunction with the"]
#[doc =
r" [`async_fn_track_caller` feature flag]. Otherwise, the `#[track_caller]`"]
#[doc = r" annotation will function as a no-op."]
#[doc = r""]
#[doc =
r" [`async_fn_track_caller` feature flag]: https://doc.rust-lang.org/beta/unstable-book/language-features/async-fn-track-caller.html"]
static UNGATED_ASYNC_FN_TRACK_CALLER: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNGATED_ASYNC_FN_TRACK_CALLER",
            default_level: ::rustc_lint_defs::Warn,
            desc: "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1128    /// The `ungated_async_fn_track_caller` lint warns when the
1129    /// `#[track_caller]` attribute is used on an async function
1130    /// without enabling the corresponding unstable feature flag.
1131    ///
1132    /// ### Example
1133    ///
1134    /// ```rust
1135    /// #[track_caller]
1136    /// async fn foo() {}
1137    /// ```
1138    ///
1139    /// {{produces}}
1140    ///
1141    /// ### Explanation
1142    ///
1143    /// The attribute must be used in conjunction with the
1144    /// [`async_fn_track_caller` feature flag]. Otherwise, the `#[track_caller]`
1145    /// annotation will function as a no-op.
1146    ///
1147    /// [`async_fn_track_caller` feature flag]: https://doc.rust-lang.org/beta/unstable-book/language-features/async-fn-track-caller.html
1148    UNGATED_ASYNC_FN_TRACK_CALLER,
1149    Warn,
1150    "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled"
1151}
1152
1153#[doc =
r" Explains corresponding feature flag must be enabled for the `#[track_caller]` attribute to"]
#[doc = r" do anything"]
pub struct UngatedAsyncFnTrackCaller;
#[automatically_derived]
impl ::core::marker::Copy for UngatedAsyncFnTrackCaller { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UngatedAsyncFnTrackCaller { }
#[automatically_derived]
impl ::core::clone::Clone for UngatedAsyncFnTrackCaller {
    #[inline]
    fn clone(&self) -> UngatedAsyncFnTrackCaller { *self }
}
impl ::rustc_lint_defs::LintPass for UngatedAsyncFnTrackCaller {
    fn name(&self) -> &'static str { "UngatedAsyncFnTrackCaller" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNGATED_ASYNC_FN_TRACK_CALLER]))
    }
}
impl UngatedAsyncFnTrackCaller {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNGATED_ASYNC_FN_TRACK_CALLER]))
    }
}declare_lint_pass!(
1154    /// Explains corresponding feature flag must be enabled for the `#[track_caller]` attribute to
1155    /// do anything
1156    UngatedAsyncFnTrackCaller => [UNGATED_ASYNC_FN_TRACK_CALLER]
1157);
1158
1159impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller {
1160    fn check_fn(
1161        &mut self,
1162        cx: &LateContext<'_>,
1163        fn_kind: HirFnKind<'_>,
1164        _: &'tcx FnDecl<'_>,
1165        _: &'tcx Body<'_>,
1166        span: Span,
1167        def_id: LocalDefId,
1168    ) {
1169        if fn_kind.asyncness().is_async()
1170            && !cx.tcx.features().async_fn_track_caller()
1171            // Now, check if the function has the `#[track_caller]` attribute
1172            && let Some(attr_span) = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &cx.tcx)
                {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(TrackCaller(span)) => {
                        break 'done Some(*span);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(cx.tcx, def_id, TrackCaller(span) => *span)
1173        {
1174            cx.emit_span_lint(
1175                UNGATED_ASYNC_FN_TRACK_CALLER,
1176                attr_span,
1177                BuiltinUngatedAsyncFnTrackCaller { label: span, session: &cx.tcx.sess },
1178            );
1179        }
1180    }
1181}
1182
1183#[doc =
r" The `unreachable_pub` lint triggers for `pub` items not reachable from other crates - that"]
#[doc =
r" means neither directly accessible, nor reexported (with `pub use`), nor leaked through"]
#[doc =
r" things like return types (which the [`unnameable_types`] lint can detect if desired)."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unreachable_pub)]"]
#[doc = r" mod foo {"]
#[doc = r"     pub mod bar {"]
#[doc = r""]
#[doc = r"     }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The `pub` keyword both expresses an intent for an item to be publicly available, and also"]
#[doc =
r" signals to the compiler to make the item publicly accessible. The intent can only be"]
#[doc =
r" satisfied, however, if all items which contain this item are *also* publicly accessible."]
#[doc =
r" Thus, this lint serves to identify situations where the intent does not match the reality."]
#[doc = r""]
#[doc =
r" If you wish the item to be accessible elsewhere within the crate, but not outside it, the"]
#[doc =
r" `pub(crate)` visibility is recommended to be used instead. This more clearly expresses the"]
#[doc = r" intent that the item is only visible within its own crate."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it will trigger for a large amount of existing Rust code."#]
#[doc = r" Eventually it is desired for this to become warn-by-default."]
#[doc = r""]
#[doc = r" [`unnameable_types`]: #unnameable-types"]
pub static UNREACHABLE_PUB: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "UNREACHABLE_PUB",
            default_level: ::rustc_lint_defs::Allow,
            desc: "`pub` items not reachable from crate root",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1184    /// The `unreachable_pub` lint triggers for `pub` items not reachable from other crates - that
1185    /// means neither directly accessible, nor reexported (with `pub use`), nor leaked through
1186    /// things like return types (which the [`unnameable_types`] lint can detect if desired).
1187    ///
1188    /// ### Example
1189    ///
1190    /// ```rust,compile_fail
1191    /// #![deny(unreachable_pub)]
1192    /// mod foo {
1193    ///     pub mod bar {
1194    ///
1195    ///     }
1196    /// }
1197    /// ```
1198    ///
1199    /// {{produces}}
1200    ///
1201    /// ### Explanation
1202    ///
1203    /// The `pub` keyword both expresses an intent for an item to be publicly available, and also
1204    /// signals to the compiler to make the item publicly accessible. The intent can only be
1205    /// satisfied, however, if all items which contain this item are *also* publicly accessible.
1206    /// Thus, this lint serves to identify situations where the intent does not match the reality.
1207    ///
1208    /// If you wish the item to be accessible elsewhere within the crate, but not outside it, the
1209    /// `pub(crate)` visibility is recommended to be used instead. This more clearly expresses the
1210    /// intent that the item is only visible within its own crate.
1211    ///
1212    /// This lint is "allow" by default because it will trigger for a large amount of existing Rust code.
1213    /// Eventually it is desired for this to become warn-by-default.
1214    ///
1215    /// [`unnameable_types`]: #unnameable-types
1216    pub UNREACHABLE_PUB,
1217    Allow,
1218    "`pub` items not reachable from crate root"
1219}
1220
1221#[doc =
r" Lint for items marked `pub` that aren't reachable from other crates."]
pub struct UnreachablePub;
#[automatically_derived]
impl ::core::marker::Copy for UnreachablePub { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnreachablePub { }
#[automatically_derived]
impl ::core::clone::Clone for UnreachablePub {
    #[inline]
    fn clone(&self) -> UnreachablePub { *self }
}
impl ::rustc_lint_defs::LintPass for UnreachablePub {
    fn name(&self) -> &'static str { "UnreachablePub" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNREACHABLE_PUB]))
    }
}
impl UnreachablePub {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [UNREACHABLE_PUB]))
    }
}declare_lint_pass!(
1222    /// Lint for items marked `pub` that aren't reachable from other crates.
1223    UnreachablePub => [UNREACHABLE_PUB]
1224);
1225
1226impl UnreachablePub {
1227    fn perform_lint(
1228        &self,
1229        cx: &LateContext<'_>,
1230        what: &str,
1231        def_id: LocalDefId,
1232        vis_span: Span,
1233        exportable: bool,
1234    ) {
1235        let mut applicability = Applicability::MachineApplicable;
1236        if cx.tcx.visibility(def_id).is_public() && !cx.effective_visibilities.is_reachable(def_id)
1237        {
1238            // prefer suggesting `pub(super)` instead of `pub(crate)` when possible,
1239            // except when `pub(super) == pub(crate)`
1240            let new_vis = if let Some(ty::Visibility::Restricted(restricted_did)) =
1241                cx.effective_visibilities.effective_vis(def_id).map(|effective_vis| {
1242                    effective_vis.at_level(rustc_middle::middle::privacy::Level::Reachable)
1243                })
1244                && let parent_parent = cx
1245                    .tcx
1246                    .parent_module_from_def_id(cx.tcx.parent_module_from_def_id(def_id).into())
1247                && *restricted_did == parent_parent.to_local_def_id()
1248                && !restricted_did.to_def_id().is_crate_root()
1249            {
1250                "pub(super)"
1251            } else {
1252                "pub(crate)"
1253            };
1254
1255            if vis_span.from_expansion() {
1256                applicability = Applicability::MaybeIncorrect;
1257            }
1258            let def_span = cx.tcx.def_span(def_id);
1259            cx.emit_span_lint(
1260                UNREACHABLE_PUB,
1261                def_span,
1262                BuiltinUnreachablePub {
1263                    what,
1264                    new_vis,
1265                    suggestion: (vis_span, applicability),
1266                    help: exportable,
1267                },
1268            );
1269        }
1270    }
1271}
1272
1273impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
1274    fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1275        // Do not warn for fake `use` statements.
1276        if let hir::ItemKind::Use(_, hir::UseKind::ListStem) = &item.kind {
1277            return;
1278        }
1279        self.perform_lint(cx, "item", item.owner_id.def_id, item.vis_span, true);
1280    }
1281
1282    fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) {
1283        self.perform_lint(cx, "item", foreign_item.owner_id.def_id, foreign_item.vis_span, true);
1284    }
1285
1286    fn check_field_def(&mut self, _cx: &LateContext<'_>, _field: &hir::FieldDef<'_>) {
1287        // - If an ADT definition is reported then we don't need to check fields
1288        //   (as it would add unnecessary complexity to the source code, the struct
1289        //   definition is in the immediate proximity to give the "real" visibility).
1290        // - If an ADT is not reported because it's not `pub` - we don't need to
1291        //   check fields.
1292        // - If an ADT is not reported because it's reachable - we also don't need
1293        //   to check fields because then they are reachable by construction if they
1294        //   are pub.
1295        //
1296        // Therefore in no case we check the fields.
1297        //
1298        // cf. https://github.com/rust-lang/rust/pull/126013#issuecomment-2152839205
1299        // cf. https://github.com/rust-lang/rust/pull/126040#issuecomment-2152944506
1300    }
1301
1302    fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
1303        if let ImplItemImplKind::Inherent { vis_span } = impl_item.impl_kind {
1304            self.perform_lint(cx, "item", impl_item.owner_id.def_id, vis_span, false);
1305        }
1306    }
1307}
1308
1309#[doc = r" The `type_alias_bounds` lint detects bounds in type aliases."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" type SendVec<T: Send> = Vec<T>;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Trait and lifetime bounds on generic parameters and in where clauses of"]
#[doc =
r" type aliases are not checked at usage sites of the type alias. Moreover,"]
#[doc =
r" they are not thoroughly checked for correctness at their definition site"]
#[doc = r" either similar to the aliased type."]
#[doc = r""]
#[doc =
r" This is a known limitation of the type checker that may be lifted in a"]
#[doc =
r" future edition. Permitting such bounds in light of this was unintentional."]
#[doc = r""]
#[doc =
r" While these bounds may have secondary effects such as enabling the use of"]
#[doc =
r#" "shorthand" associated type paths[^1] and affecting the default trait"#]
#[doc =
r" object lifetime[^2] of trait object types passed to the type alias, this"]
#[doc =
r" should not have been allowed until the aforementioned restrictions of the"]
#[doc = r" type checker have been lifted."]
#[doc = r""]
#[doc =
r" Using such bounds is highly discouraged as they are actively misleading."]
#[doc = r""]
#[doc =
r" [^1]: I.e., paths of the form `T::Assoc` where `T` is a type parameter"]
#[doc =
r" bounded by trait `Trait` which defines an associated type called `Assoc`"]
#[doc =
r" as opposed to a fully qualified path of the form `<T as Trait>::Assoc`."]
#[doc =
r" [^2]: <https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes>"]
static TYPE_ALIAS_BOUNDS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "TYPE_ALIAS_BOUNDS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "bounds in type aliases are not enforced",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1310    /// The `type_alias_bounds` lint detects bounds in type aliases.
1311    ///
1312    /// ### Example
1313    ///
1314    /// ```rust
1315    /// type SendVec<T: Send> = Vec<T>;
1316    /// ```
1317    ///
1318    /// {{produces}}
1319    ///
1320    /// ### Explanation
1321    ///
1322    /// Trait and lifetime bounds on generic parameters and in where clauses of
1323    /// type aliases are not checked at usage sites of the type alias. Moreover,
1324    /// they are not thoroughly checked for correctness at their definition site
1325    /// either similar to the aliased type.
1326    ///
1327    /// This is a known limitation of the type checker that may be lifted in a
1328    /// future edition. Permitting such bounds in light of this was unintentional.
1329    ///
1330    /// While these bounds may have secondary effects such as enabling the use of
1331    /// "shorthand" associated type paths[^1] and affecting the default trait
1332    /// object lifetime[^2] of trait object types passed to the type alias, this
1333    /// should not have been allowed until the aforementioned restrictions of the
1334    /// type checker have been lifted.
1335    ///
1336    /// Using such bounds is highly discouraged as they are actively misleading.
1337    ///
1338    /// [^1]: I.e., paths of the form `T::Assoc` where `T` is a type parameter
1339    /// bounded by trait `Trait` which defines an associated type called `Assoc`
1340    /// as opposed to a fully qualified path of the form `<T as Trait>::Assoc`.
1341    /// [^2]: <https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes>
1342    TYPE_ALIAS_BOUNDS,
1343    Warn,
1344    "bounds in type aliases are not enforced"
1345}
1346
1347pub struct TypeAliasBounds;
#[automatically_derived]
impl ::core::marker::Copy for TypeAliasBounds { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TypeAliasBounds { }
#[automatically_derived]
impl ::core::clone::Clone for TypeAliasBounds {
    #[inline]
    fn clone(&self) -> TypeAliasBounds { *self }
}
impl ::rustc_lint_defs::LintPass for TypeAliasBounds {
    fn name(&self) -> &'static str { "TypeAliasBounds" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [TYPE_ALIAS_BOUNDS]))
    }
}
impl TypeAliasBounds {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [TYPE_ALIAS_BOUNDS]))
    }
}declare_lint_pass!(TypeAliasBounds => [TYPE_ALIAS_BOUNDS]);
1348
1349impl TypeAliasBounds {
1350    pub(crate) fn affects_object_lifetime_defaults(pred: &hir::WherePredicate<'_>) -> bool {
1351        // Bounds of the form `T: 'a` with `T` type param affect object lifetime defaults.
1352        if let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind
1353            && pred.bounds.iter().any(|bound| #[allow(non_exhaustive_omitted_patterns)] match bound {
    hir::GenericBound::Outlives(_) => true,
    _ => false,
}matches!(bound, hir::GenericBound::Outlives(_)))
1354            && pred.bound_generic_params.is_empty() // indeed, even if absent from the RHS
1355            && pred.bounded_ty.as_generic_param().is_some()
1356        {
1357            return true;
1358        }
1359        false
1360    }
1361}
1362
1363impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds {
1364    fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1365        let hir::ItemKind::TyAlias(_, generics, hir_ty) = item.kind else { return };
1366
1367        // There must not be a where clause.
1368        if generics.predicates.is_empty() {
1369            return;
1370        }
1371
1372        // Bounds of lazy type aliases and TAITs are respected.
1373        if cx.tcx.type_alias_is_lazy(item.owner_id) {
1374            return;
1375        }
1376
1377        // FIXME(generic_const_exprs): Revisit this before stabilization.
1378        // See also `tests/ui/const-generics/generic_const_exprs/type-alias-bounds.rs`.
1379        let ty = cx.tcx.type_of(item.owner_id).instantiate_identity();
1380        if ty.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION)
1381            && cx.tcx.features().generic_const_exprs()
1382        {
1383            return;
1384        }
1385
1386        // NOTE(inherent_associated_types): While we currently do take some bounds in type
1387        // aliases into consideration during IAT *selection*, we don't perform full use+def
1388        // site wfchecking for such type aliases. Therefore TAB should still trigger.
1389        // See also `tests/ui/associated-inherent-types/type-alias-bounds.rs`.
1390
1391        let mut where_spans = Vec::new();
1392        let mut inline_spans = Vec::new();
1393        let mut inline_sugg = Vec::new();
1394
1395        for p in generics.predicates {
1396            let span = p.span;
1397            if p.kind.in_where_clause() {
1398                where_spans.push(span);
1399            } else {
1400                for b in p.kind.bounds() {
1401                    inline_spans.push(b.span());
1402                }
1403                inline_sugg.push((span, String::new()));
1404            }
1405        }
1406
1407        let mut ty = Some(hir_ty);
1408        let enable_feat_help = cx.tcx.sess.is_nightly_build();
1409
1410        if let [.., label_sp] = *where_spans {
1411            cx.emit_span_lint(
1412                TYPE_ALIAS_BOUNDS,
1413                where_spans,
1414                BuiltinTypeAliasBounds {
1415                    in_where_clause: true,
1416                    label: label_sp,
1417                    enable_feat_help,
1418                    suggestions: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(generics.where_clause_span, String::new())]))vec![(generics.where_clause_span, String::new())],
1419                    preds: generics.predicates,
1420                    ty: ty.take(),
1421                },
1422            );
1423        }
1424        if let [.., label_sp] = *inline_spans {
1425            cx.emit_span_lint(
1426                TYPE_ALIAS_BOUNDS,
1427                inline_spans,
1428                BuiltinTypeAliasBounds {
1429                    in_where_clause: false,
1430                    label: label_sp,
1431                    enable_feat_help,
1432                    suggestions: inline_sugg,
1433                    preds: generics.predicates,
1434                    ty,
1435                },
1436            );
1437        }
1438    }
1439}
1440
1441pub(crate) struct ShorthandAssocTyCollector {
1442    pub(crate) qselves: Vec<Span>,
1443}
1444
1445impl hir::intravisit::Visitor<'_> for ShorthandAssocTyCollector {
1446    fn visit_qpath(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, _: Span) {
1447        // Look for "type-parameter shorthand-associated-types". I.e., paths of the
1448        // form `T::Assoc` with `T` type param. These are reliant on trait bounds.
1449        if let hir::QPath::TypeRelative(qself, _) = qpath
1450            && qself.as_generic_param().is_some()
1451        {
1452            self.qselves.push(qself.span);
1453        }
1454        hir::intravisit::walk_qpath(self, qpath, id)
1455    }
1456}
1457
1458#[doc =
r" The `trivial_bounds` lint detects trait bounds that don't depend on"]
#[doc = r" any type parameters."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(trivial_bounds)]"]
#[doc = r" pub struct A where i32: Copy;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Usually you would not write a trait bound that you know is always"]
#[doc =
r" true, or never true. However, when using macros, the macro may not"]
#[doc =
r" know whether or not the constraint would hold or not at the time when"]
#[doc =
r" generating the code. Currently, the compiler does not alert you if the"]
#[doc =
r" constraint is always true, and generates an error if it is never true."]
#[doc = r" The `trivial_bounds` feature changes this to be a warning in both"]
#[doc =
r" cases, giving macros more freedom and flexibility to generate code,"]
#[doc = r" while still providing a signal when writing non-macro code that"]
#[doc = r" something is amiss."]
#[doc = r""]
#[doc = r" See [RFC 2056] for more details. This feature is currently only"]
#[doc = r" available on the nightly channel, see [tracking issue #48214]."]
#[doc = r""]
#[doc =
r" [RFC 2056]: https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md"]
#[doc =
r" [tracking issue #48214]: https://github.com/rust-lang/rust/issues/48214"]
static TRIVIAL_BOUNDS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "TRIVIAL_BOUNDS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "these bounds don't depend on an type parameters",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1459    /// The `trivial_bounds` lint detects trait bounds that don't depend on
1460    /// any type parameters.
1461    ///
1462    /// ### Example
1463    ///
1464    /// ```rust
1465    /// #![feature(trivial_bounds)]
1466    /// pub struct A where i32: Copy;
1467    /// ```
1468    ///
1469    /// {{produces}}
1470    ///
1471    /// ### Explanation
1472    ///
1473    /// Usually you would not write a trait bound that you know is always
1474    /// true, or never true. However, when using macros, the macro may not
1475    /// know whether or not the constraint would hold or not at the time when
1476    /// generating the code. Currently, the compiler does not alert you if the
1477    /// constraint is always true, and generates an error if it is never true.
1478    /// The `trivial_bounds` feature changes this to be a warning in both
1479    /// cases, giving macros more freedom and flexibility to generate code,
1480    /// while still providing a signal when writing non-macro code that
1481    /// something is amiss.
1482    ///
1483    /// See [RFC 2056] for more details. This feature is currently only
1484    /// available on the nightly channel, see [tracking issue #48214].
1485    ///
1486    /// [RFC 2056]: https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md
1487    /// [tracking issue #48214]: https://github.com/rust-lang/rust/issues/48214
1488    TRIVIAL_BOUNDS,
1489    Warn,
1490    "these bounds don't depend on an type parameters"
1491}
1492
1493#[doc =
r" Lint for trait and lifetime bounds that don't depend on type parameters"]
#[doc = r" which either do nothing, or stop the item from being used."]
pub struct TrivialConstraints;
#[automatically_derived]
impl ::core::marker::Copy for TrivialConstraints { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TrivialConstraints { }
#[automatically_derived]
impl ::core::clone::Clone for TrivialConstraints {
    #[inline]
    fn clone(&self) -> TrivialConstraints { *self }
}
impl ::rustc_lint_defs::LintPass for TrivialConstraints {
    fn name(&self) -> &'static str { "TrivialConstraints" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [TRIVIAL_BOUNDS]))
    }
}
impl TrivialConstraints {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [TRIVIAL_BOUNDS]))
    }
}declare_lint_pass!(
1494    /// Lint for trait and lifetime bounds that don't depend on type parameters
1495    /// which either do nothing, or stop the item from being used.
1496    TrivialConstraints => [TRIVIAL_BOUNDS]
1497);
1498
1499impl<'tcx> LateLintPass<'tcx> for TrivialConstraints {
1500    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
1501        use rustc_middle::ty::ClauseKind;
1502
1503        if cx.tcx.features().trivial_bounds() {
1504            let predicates = cx.tcx.predicates_of(item.owner_id);
1505            for &(predicate, span) in predicates.predicates {
1506                let predicate_kind_name = match predicate.kind().skip_binder() {
1507                    ClauseKind::Trait(..) => "trait",
1508                    ClauseKind::TypeOutlives(..) |
1509                    ClauseKind::RegionOutlives(..) => "lifetime",
1510
1511                    ClauseKind::UnstableFeature(_)
1512                    // `ConstArgHasType` is never global as `ct` is always a param
1513                    | ClauseKind::ConstArgHasType(..)
1514                    // Ignore projections, as they can only be global
1515                    // if the trait bound is global
1516                    | ClauseKind::Projection(..)
1517                    // Ignore bounds that a user can't type
1518                    | ClauseKind::WellFormed(..)
1519                    // FIXME(generic_const_exprs): `ConstEvaluatable` can be written
1520                    | ClauseKind::ConstEvaluatable(..)
1521                    // Users don't write this directly, only via another trait ref.
1522                    | ty::ClauseKind::HostEffect(..) => continue,
1523                };
1524                if predicate.is_global() {
1525                    cx.emit_span_lint(
1526                        TRIVIAL_BOUNDS,
1527                        span,
1528                        BuiltinTrivialBounds { predicate_kind_name, predicate },
1529                    );
1530                }
1531            }
1532        }
1533    }
1534}
1535
1536#[doc =
r" The `double_negations` lint detects expressions of the form `--x`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn main() {"]
#[doc = r"     let x = 1;"]
#[doc = r"     let _b = --x;"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Negating something twice is usually the same as not negating it at all."]
#[doc =
r" However, a double negation in Rust can easily be confused with the"]
#[doc =
r" prefix decrement operator that exists in many languages derived from C."]
#[doc = r" Use `-(-x)` if you really wanted to negate the value twice."]
#[doc = r""]
#[doc = r" To decrement a value, use `x -= 1` instead."]
pub static DOUBLE_NEGATIONS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "DOUBLE_NEGATIONS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "detects expressions of the form `--x`",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1537    /// The `double_negations` lint detects expressions of the form `--x`.
1538    ///
1539    /// ### Example
1540    ///
1541    /// ```rust
1542    /// fn main() {
1543    ///     let x = 1;
1544    ///     let _b = --x;
1545    /// }
1546    /// ```
1547    ///
1548    /// {{produces}}
1549    ///
1550    /// ### Explanation
1551    ///
1552    /// Negating something twice is usually the same as not negating it at all.
1553    /// However, a double negation in Rust can easily be confused with the
1554    /// prefix decrement operator that exists in many languages derived from C.
1555    /// Use `-(-x)` if you really wanted to negate the value twice.
1556    ///
1557    /// To decrement a value, use `x -= 1` instead.
1558    pub DOUBLE_NEGATIONS,
1559    Warn,
1560    "detects expressions of the form `--x`"
1561}
1562
1563#[doc =
r" Lint for expressions of the form `--x` that can be confused with C's"]
#[doc = r" prefix decrement operator."]
pub struct DoubleNegations;
#[automatically_derived]
impl ::core::marker::Copy for DoubleNegations { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DoubleNegations { }
#[automatically_derived]
impl ::core::clone::Clone for DoubleNegations {
    #[inline]
    fn clone(&self) -> DoubleNegations { *self }
}
impl ::rustc_lint_defs::LintPass for DoubleNegations {
    fn name(&self) -> &'static str { "DoubleNegations" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DOUBLE_NEGATIONS]))
    }
}
impl DoubleNegations {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DOUBLE_NEGATIONS]))
    }
}declare_lint_pass!(
1564    /// Lint for expressions of the form `--x` that can be confused with C's
1565    /// prefix decrement operator.
1566    DoubleNegations => [DOUBLE_NEGATIONS]
1567);
1568
1569impl EarlyLintPass for DoubleNegations {
1570    #[inline]
1571    fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
1572        // only lint on the innermost `--` in a chain of `-` operators,
1573        // even if there are 3 or more negations
1574        if let ExprKind::Unary(UnOp::Neg, ref inner) = expr.kind
1575            && let ExprKind::Unary(UnOp::Neg, ref inner2) = inner.kind
1576            && !#[allow(non_exhaustive_omitted_patterns)] match inner2.kind {
    ExprKind::Unary(UnOp::Neg, _) => true,
    _ => false,
}matches!(inner2.kind, ExprKind::Unary(UnOp::Neg, _))
1577            // Don't lint if this jumps macro expansion boundary (Issue #143980)
1578            && expr.span.eq_ctxt(inner.span)
1579        {
1580            cx.emit_span_lint(
1581                DOUBLE_NEGATIONS,
1582                expr.span,
1583                BuiltinDoubleNegations {
1584                    add_parens: BuiltinDoubleNegationsAddParens {
1585                        start_span: inner.span.shrink_to_lo(),
1586                        end_span: inner.span.shrink_to_hi(),
1587                    },
1588                },
1589            );
1590        }
1591    }
1592}
1593
1594#[doc = r" Does nothing as a lint pass, but registers some `Lint`s"]
#[doc = r" which are used by other parts of the compiler."]
pub struct SoftLints;
#[automatically_derived]
impl ::core::marker::Copy for SoftLints { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SoftLints { }
#[automatically_derived]
impl ::core::clone::Clone for SoftLints {
    #[inline]
    fn clone(&self) -> SoftLints { *self }
}
impl ::rustc_lint_defs::LintPass for SoftLints {
    fn name(&self) -> &'static str { "SoftLints" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [WHILE_TRUE, NON_SHORTHAND_FIELD_PATTERNS, UNSAFE_CODE,
                        MISSING_DOCS, MISSING_COPY_IMPLEMENTATIONS,
                        MISSING_DEBUG_IMPLEMENTATIONS, ANONYMOUS_PARAMETERS,
                        UNUSED_DOC_COMMENTS, NO_MANGLE_CONST_ITEMS,
                        NO_MANGLE_GENERIC_ITEMS, MUTABLE_TRANSMUTES,
                        UNSTABLE_FEATURES, UNREACHABLE_PUB, TYPE_ALIAS_BOUNDS,
                        TRIVIAL_BOUNDS, DOUBLE_NEGATIONS]))
    }
}
impl SoftLints {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [WHILE_TRUE, NON_SHORTHAND_FIELD_PATTERNS, UNSAFE_CODE,
                        MISSING_DOCS, MISSING_COPY_IMPLEMENTATIONS,
                        MISSING_DEBUG_IMPLEMENTATIONS, ANONYMOUS_PARAMETERS,
                        UNUSED_DOC_COMMENTS, NO_MANGLE_CONST_ITEMS,
                        NO_MANGLE_GENERIC_ITEMS, MUTABLE_TRANSMUTES,
                        UNSTABLE_FEATURES, UNREACHABLE_PUB, TYPE_ALIAS_BOUNDS,
                        TRIVIAL_BOUNDS, DOUBLE_NEGATIONS]))
    }
}declare_lint_pass!(
1595    /// Does nothing as a lint pass, but registers some `Lint`s
1596    /// which are used by other parts of the compiler.
1597    SoftLints => [
1598        WHILE_TRUE,
1599        NON_SHORTHAND_FIELD_PATTERNS,
1600        UNSAFE_CODE,
1601        MISSING_DOCS,
1602        MISSING_COPY_IMPLEMENTATIONS,
1603        MISSING_DEBUG_IMPLEMENTATIONS,
1604        ANONYMOUS_PARAMETERS,
1605        UNUSED_DOC_COMMENTS,
1606        NO_MANGLE_CONST_ITEMS,
1607        NO_MANGLE_GENERIC_ITEMS,
1608        MUTABLE_TRANSMUTES,
1609        UNSTABLE_FEATURES,
1610        UNREACHABLE_PUB,
1611        TYPE_ALIAS_BOUNDS,
1612        TRIVIAL_BOUNDS,
1613        DOUBLE_NEGATIONS
1614    ]
1615);
1616
1617#[doc =
r" The `ellipsis_inclusive_range_patterns` lint detects the [`...` range"]
#[doc = r" pattern], which is deprecated."]
#[doc = r""]
#[doc =
r" [`...` range pattern]: https://doc.rust-lang.org/reference/patterns.html#range-patterns"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2018"]
#[doc = r" let x = 123;"]
#[doc = r" match x {"]
#[doc = r"     0...100 => {}"]
#[doc = r"     _ => {}"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The `...` range pattern syntax was changed to `..=` to avoid potential"]
#[doc =
r" confusion with the [`..` range expression]. Use the new form instead."]
#[doc = r""]
#[doc =
r" [`..` range expression]: https://doc.rust-lang.org/reference/expressions/range-expr.html"]
pub static ELLIPSIS_INCLUSIVE_RANGE_PATTERNS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "ELLIPSIS_INCLUSIVE_RANGE_PATTERNS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "`...` range patterns are deprecated",
            is_externally_loaded: false,
            future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
                    reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
                            edition: rustc_span::edition::Edition::Edition2021,
                            page_slug: "warnings-promoted-to-error",
                        }),
                    ..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
                }),
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1618    /// The `ellipsis_inclusive_range_patterns` lint detects the [`...` range
1619    /// pattern], which is deprecated.
1620    ///
1621    /// [`...` range pattern]: https://doc.rust-lang.org/reference/patterns.html#range-patterns
1622    ///
1623    /// ### Example
1624    ///
1625    /// ```rust,edition2018
1626    /// let x = 123;
1627    /// match x {
1628    ///     0...100 => {}
1629    ///     _ => {}
1630    /// }
1631    /// ```
1632    ///
1633    /// {{produces}}
1634    ///
1635    /// ### Explanation
1636    ///
1637    /// The `...` range pattern syntax was changed to `..=` to avoid potential
1638    /// confusion with the [`..` range expression]. Use the new form instead.
1639    ///
1640    /// [`..` range expression]: https://doc.rust-lang.org/reference/expressions/range-expr.html
1641    pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1642    Warn,
1643    "`...` range patterns are deprecated",
1644    @future_incompatible = FutureIncompatibleInfo {
1645        reason: fcw!(EditionError 2021 "warnings-promoted-to-error"),
1646    };
1647}
1648
1649#[derive(#[automatically_derived]
impl ::core::default::Default for EllipsisInclusiveRangePatterns {
    #[inline]
    fn default() -> EllipsisInclusiveRangePatterns {
        EllipsisInclusiveRangePatterns {
            node_id: ::core::default::Default::default(),
        }
    }
}Default)]
1650pub struct EllipsisInclusiveRangePatterns {
1651    /// If `Some(_)`, suppress all subsequent pattern
1652    /// warnings for better diagnostics.
1653    node_id: Option<ast::NodeId>,
1654}
1655
1656impl ::rustc_lint_defs::LintPass for EllipsisInclusiveRangePatterns {
    fn name(&self) -> &'static str { "EllipsisInclusiveRangePatterns" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]))
    }
}
impl EllipsisInclusiveRangePatterns {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]))
    }
}impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1657
1658impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1659    fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1660        if self.node_id.is_some() {
1661            // Don't recursively warn about patterns inside range endpoints.
1662            return;
1663        }
1664
1665        use self::ast::PatKind;
1666        use self::ast::RangeSyntax::DotDotDot;
1667
1668        /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1669        /// corresponding to the ellipsis.
1670        fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> {
1671            match &pat.kind {
1672                PatKind::Range(
1673                    a,
1674                    Some(b),
1675                    Spanned { span, node: RangeEnd::Included(DotDotDot) },
1676                ) => Some((a.as_deref(), b, *span)),
1677                _ => None,
1678            }
1679        }
1680
1681        let (parentheses, endpoints) = match &pat.kind {
1682            PatKind::Ref(subpat, _, _) => (true, matches_ellipsis_pat(subpat)),
1683            _ => (false, matches_ellipsis_pat(pat)),
1684        };
1685
1686        if let Some((start, end, join)) = endpoints {
1687            if parentheses {
1688                self.node_id = Some(pat.id);
1689                let end = expr_to_string(end);
1690                let replace = match start {
1691                    Some(start) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&({0}..={1})",
                expr_to_string(start), end))
    })format!("&({}..={})", expr_to_string(start), end),
1692                    None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&(..={0})", end))
    })format!("&(..={end})"),
1693                };
1694                if join.edition() >= Edition::Edition2021 {
1695                    cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1696                        span: pat.span,
1697                        suggestion: pat.span,
1698                        replace,
1699                    });
1700                } else {
1701                    cx.emit_span_lint(
1702                        ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1703                        pat.span,
1704                        BuiltinEllipsisInclusiveRangePatternsLint::Parenthesise {
1705                            suggestion: pat.span,
1706                            replace,
1707                        },
1708                    );
1709                }
1710            } else {
1711                let replace = "..=";
1712                if join.edition() >= Edition::Edition2021 {
1713                    cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1714                        span: pat.span,
1715                        suggestion: join,
1716                        replace: replace.to_string(),
1717                    });
1718                } else {
1719                    cx.emit_span_lint(
1720                        ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1721                        join,
1722                        BuiltinEllipsisInclusiveRangePatternsLint::NonParenthesise {
1723                            suggestion: join,
1724                        },
1725                    );
1726                }
1727            };
1728        }
1729    }
1730
1731    fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1732        if let Some(node_id) = self.node_id {
1733            if pat.id == node_id {
1734                self.node_id = None
1735            }
1736        }
1737    }
1738}
1739
1740#[doc =
r" The `keyword_idents_2018` lint detects edition keywords being used as an"]
#[doc = r" identifier."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(keyword_idents_2018)]"]
#[doc = r" // edition 2015"]
#[doc = r" fn dyn() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Rust [editions] allow the language to evolve without breaking"]
#[doc =
r" backwards compatibility. This lint catches code that uses new keywords"]
#[doc =
r" that are added to the language that are used as identifiers (such as a"]
#[doc =
r" variable name, function name, etc.). If you switch the compiler to a"]
#[doc =
r" new edition without updating the code, then it will fail to compile if"]
#[doc = r" you are using a new keyword as an identifier."]
#[doc = r""]
#[doc =
r" You can manually change the identifiers to a non-keyword, or use a"]
#[doc =
r" [raw identifier], for example `r#dyn`, to transition to a new edition."]
#[doc = r""]
#[doc =
r#" This lint solves the problem automatically. It is "allow" by default"#]
#[doc =
r" because the code is perfectly valid in older editions. The [`cargo"]
#[doc =
r#" fix`] tool with the `--edition` flag will switch this lint to "warn""#]
#[doc =
r" and automatically apply the suggested fix from the compiler (which is"]
#[doc =
r" to use a raw identifier). This provides a completely automated way to"]
#[doc = r" update old code for a new edition."]
#[doc = r""]
#[doc = r" [editions]: https://doc.rust-lang.org/edition-guide/"]
#[doc =
r" [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static KEYWORD_IDENTS_2018: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "KEYWORD_IDENTS_2018",
            default_level: ::rustc_lint_defs::Allow,
            desc: "detects edition keywords being used as an identifier",
            is_externally_loaded: false,
            future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
                    reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
                            edition: rustc_span::edition::Edition::Edition2018,
                            page_slug: "new-keywords",
                        }),
                    ..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
                }),
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1741    /// The `keyword_idents_2018` lint detects edition keywords being used as an
1742    /// identifier.
1743    ///
1744    /// ### Example
1745    ///
1746    /// ```rust,edition2015,compile_fail
1747    /// #![deny(keyword_idents_2018)]
1748    /// // edition 2015
1749    /// fn dyn() {}
1750    /// ```
1751    ///
1752    /// {{produces}}
1753    ///
1754    /// ### Explanation
1755    ///
1756    /// Rust [editions] allow the language to evolve without breaking
1757    /// backwards compatibility. This lint catches code that uses new keywords
1758    /// that are added to the language that are used as identifiers (such as a
1759    /// variable name, function name, etc.). If you switch the compiler to a
1760    /// new edition without updating the code, then it will fail to compile if
1761    /// you are using a new keyword as an identifier.
1762    ///
1763    /// You can manually change the identifiers to a non-keyword, or use a
1764    /// [raw identifier], for example `r#dyn`, to transition to a new edition.
1765    ///
1766    /// This lint solves the problem automatically. It is "allow" by default
1767    /// because the code is perfectly valid in older editions. The [`cargo
1768    /// fix`] tool with the `--edition` flag will switch this lint to "warn"
1769    /// and automatically apply the suggested fix from the compiler (which is
1770    /// to use a raw identifier). This provides a completely automated way to
1771    /// update old code for a new edition.
1772    ///
1773    /// [editions]: https://doc.rust-lang.org/edition-guide/
1774    /// [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html
1775    /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1776    pub KEYWORD_IDENTS_2018,
1777    Allow,
1778    "detects edition keywords being used as an identifier",
1779    @future_incompatible = FutureIncompatibleInfo {
1780        reason: fcw!(EditionError 2018 "new-keywords"),
1781    };
1782}
1783
1784#[doc =
r" The `keyword_idents_2024` lint detects edition keywords being used as an"]
#[doc = r" identifier."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(keyword_idents_2024)]"]
#[doc = r" // edition 2015"]
#[doc = r" fn gen() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Rust [editions] allow the language to evolve without breaking"]
#[doc =
r" backwards compatibility. This lint catches code that uses new keywords"]
#[doc =
r" that are added to the language that are used as identifiers (such as a"]
#[doc =
r" variable name, function name, etc.). If you switch the compiler to a"]
#[doc =
r" new edition without updating the code, then it will fail to compile if"]
#[doc = r" you are using a new keyword as an identifier."]
#[doc = r""]
#[doc =
r" You can manually change the identifiers to a non-keyword, or use a"]
#[doc =
r" [raw identifier], for example `r#gen`, to transition to a new edition."]
#[doc = r""]
#[doc =
r#" This lint solves the problem automatically. It is "allow" by default"#]
#[doc =
r" because the code is perfectly valid in older editions. The [`cargo"]
#[doc =
r#" fix`] tool with the `--edition` flag will switch this lint to "warn""#]
#[doc =
r" and automatically apply the suggested fix from the compiler (which is"]
#[doc =
r" to use a raw identifier). This provides a completely automated way to"]
#[doc = r" update old code for a new edition."]
#[doc = r""]
#[doc = r" [editions]: https://doc.rust-lang.org/edition-guide/"]
#[doc =
r" [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static KEYWORD_IDENTS_2024: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "KEYWORD_IDENTS_2024",
            default_level: ::rustc_lint_defs::Allow,
            desc: "detects edition keywords being used as an identifier",
            is_externally_loaded: false,
            future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
                    reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
                            edition: rustc_span::edition::Edition::Edition2024,
                            page_slug: "gen-keyword",
                        }),
                    ..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
                }),
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
1785    /// The `keyword_idents_2024` lint detects edition keywords being used as an
1786    /// identifier.
1787    ///
1788    /// ### Example
1789    ///
1790    /// ```rust,edition2015,compile_fail
1791    /// #![deny(keyword_idents_2024)]
1792    /// // edition 2015
1793    /// fn gen() {}
1794    /// ```
1795    ///
1796    /// {{produces}}
1797    ///
1798    /// ### Explanation
1799    ///
1800    /// Rust [editions] allow the language to evolve without breaking
1801    /// backwards compatibility. This lint catches code that uses new keywords
1802    /// that are added to the language that are used as identifiers (such as a
1803    /// variable name, function name, etc.). If you switch the compiler to a
1804    /// new edition without updating the code, then it will fail to compile if
1805    /// you are using a new keyword as an identifier.
1806    ///
1807    /// You can manually change the identifiers to a non-keyword, or use a
1808    /// [raw identifier], for example `r#gen`, to transition to a new edition.
1809    ///
1810    /// This lint solves the problem automatically. It is "allow" by default
1811    /// because the code is perfectly valid in older editions. The [`cargo
1812    /// fix`] tool with the `--edition` flag will switch this lint to "warn"
1813    /// and automatically apply the suggested fix from the compiler (which is
1814    /// to use a raw identifier). This provides a completely automated way to
1815    /// update old code for a new edition.
1816    ///
1817    /// [editions]: https://doc.rust-lang.org/edition-guide/
1818    /// [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html
1819    /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1820    pub KEYWORD_IDENTS_2024,
1821    Allow,
1822    "detects edition keywords being used as an identifier",
1823    @future_incompatible = FutureIncompatibleInfo {
1824        reason: fcw!(EditionError 2024 "gen-keyword"),
1825    };
1826}
1827
1828#[doc = r" Check for uses of edition keywords used as an identifier."]
pub struct KeywordIdents;
#[automatically_derived]
impl ::core::marker::Copy for KeywordIdents { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for KeywordIdents { }
#[automatically_derived]
impl ::core::clone::Clone for KeywordIdents {
    #[inline]
    fn clone(&self) -> KeywordIdents { *self }
}
impl ::rustc_lint_defs::LintPass for KeywordIdents {
    fn name(&self) -> &'static str { "KeywordIdents" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]))
    }
}
impl KeywordIdents {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]))
    }
}declare_lint_pass!(
1829    /// Check for uses of edition keywords used as an identifier.
1830    KeywordIdents => [KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]
1831);
1832
1833struct UnderMacro(bool);
1834
1835impl KeywordIdents {
1836    fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream) {
1837        // Check if the preceding token is `$`, because we want to allow `$async`, etc.
1838        let mut prev_dollar = false;
1839        for tt in tokens.iter() {
1840            match tt {
1841                // Only report non-raw idents.
1842                TokenTree::Token(token, _) => {
1843                    if let Some((ident, token::IdentIsRaw::No)) = token.ident() {
1844                        if !prev_dollar {
1845                            self.check_ident_token(cx, UnderMacro(true), ident, "");
1846                        }
1847                    } else if let Some((ident, token::IdentIsRaw::No)) = token.lifetime() {
1848                        self.check_ident_token(
1849                            cx,
1850                            UnderMacro(true),
1851                            ident.without_first_quote(),
1852                            "'",
1853                        );
1854                    } else if token.kind == TokenKind::Dollar {
1855                        prev_dollar = true;
1856                        continue;
1857                    }
1858                }
1859                TokenTree::Delimited(.., tts) => self.check_tokens(cx, tts),
1860            }
1861            prev_dollar = false;
1862        }
1863    }
1864
1865    fn check_ident_token(
1866        &mut self,
1867        cx: &EarlyContext<'_>,
1868        UnderMacro(under_macro): UnderMacro,
1869        ident: Ident,
1870        prefix: &'static str,
1871    ) {
1872        let (lint, edition) = match ident.name {
1873            kw::Async | kw::Await | kw::Try => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1874
1875            // rust-lang/rust#56327: Conservatively do not
1876            // attempt to report occurrences of `dyn` within
1877            // macro definitions or invocations, because `dyn`
1878            // can legitimately occur as a contextual keyword
1879            // in 2015 code denoting its 2018 meaning, and we
1880            // do not want rustfix to inject bugs into working
1881            // code by rewriting such occurrences.
1882            //
1883            // But if we see `dyn` outside of a macro, we know
1884            // its precise role in the parsed AST and thus are
1885            // assured this is truly an attempt to use it as
1886            // an identifier.
1887            kw::Dyn if !under_macro => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1888
1889            kw::Gen => (KEYWORD_IDENTS_2024, Edition::Edition2024),
1890
1891            _ => return,
1892        };
1893
1894        // Don't lint `r#foo`.
1895        if ident.span.edition() >= edition
1896            || cx.sess().psess.raw_identifier_spans.contains(ident.span)
1897        {
1898            return;
1899        }
1900
1901        cx.emit_span_lint(
1902            lint,
1903            ident.span,
1904            BuiltinKeywordIdents { kw: ident, next: edition, suggestion: ident.span, prefix },
1905        );
1906    }
1907}
1908
1909impl EarlyLintPass for KeywordIdents {
1910    fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef) {
1911        self.check_tokens(cx, &mac_def.body.tokens);
1912    }
1913    fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) {
1914        self.check_tokens(cx, &mac.args.tokens);
1915    }
1916    fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: &Ident) {
1917        if ident.name.as_str().starts_with('\'') {
1918            self.check_ident_token(cx, UnderMacro(false), ident.without_first_quote(), "'");
1919        } else {
1920            self.check_ident_token(cx, UnderMacro(false), *ident, "");
1921        }
1922    }
1923}
1924
1925pub struct ExplicitOutlivesRequirements;
#[automatically_derived]
impl ::core::marker::Copy for ExplicitOutlivesRequirements { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ExplicitOutlivesRequirements { }
#[automatically_derived]
impl ::core::clone::Clone for ExplicitOutlivesRequirements {
    #[inline]
    fn clone(&self) -> ExplicitOutlivesRequirements { *self }
}
impl ::rustc_lint_defs::LintPass for ExplicitOutlivesRequirements {
    fn name(&self) -> &'static str { "ExplicitOutlivesRequirements" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [EXPLICIT_OUTLIVES_REQUIREMENTS]))
    }
}
impl ExplicitOutlivesRequirements {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [EXPLICIT_OUTLIVES_REQUIREMENTS]))
    }
}declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1926
1927impl ExplicitOutlivesRequirements {
1928    fn lifetimes_outliving_lifetime<'tcx>(
1929        tcx: TyCtxt<'tcx>,
1930        inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1931        item: LocalDefId,
1932        lifetime: LocalDefId,
1933    ) -> Vec<ty::Region<'tcx>> {
1934        let item_generics = tcx.generics_of(item);
1935
1936        inferred_outlives
1937            .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1938                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => match a.kind() {
1939                    ty::ReEarlyParam(ebr)
1940                        if item_generics.region_param(ebr, tcx).def_id == lifetime.to_def_id() =>
1941                    {
1942                        Some(b)
1943                    }
1944                    _ => None,
1945                },
1946                _ => None,
1947            })
1948            .collect()
1949    }
1950
1951    fn lifetimes_outliving_type<'tcx>(
1952        inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1953        index: u32,
1954    ) -> Vec<ty::Region<'tcx>> {
1955        inferred_outlives
1956            .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1957                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
1958                    a.is_param(index).then_some(b)
1959                }
1960                _ => None,
1961            })
1962            .collect()
1963    }
1964
1965    fn collect_outlives_bound_spans<'tcx>(
1966        &self,
1967        tcx: TyCtxt<'tcx>,
1968        bounds: &hir::GenericBounds<'_>,
1969        inferred_outlives: &[ty::Region<'tcx>],
1970        predicate_span: Span,
1971        item: DefId,
1972    ) -> Vec<(usize, Span)> {
1973        use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
1974
1975        let item_generics = tcx.generics_of(item);
1976
1977        bounds
1978            .iter()
1979            .enumerate()
1980            .filter_map(|(i, bound)| {
1981                let hir::GenericBound::Outlives(lifetime) = bound else {
1982                    return None;
1983                };
1984
1985                let is_inferred = match tcx.named_bound_var(lifetime.hir_id) {
1986                    Some(ResolvedArg::EarlyBound(def_id)) => inferred_outlives
1987                        .iter()
1988                        .any(|r| #[allow(non_exhaustive_omitted_patterns)] match r.kind() {
    ty::ReEarlyParam(ebr) if
        { item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() }
        => true,
    _ => false,
}matches!(r.kind(), ty::ReEarlyParam(ebr) if { item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() })),
1989                    _ => false,
1990                };
1991
1992                if !is_inferred {
1993                    return None;
1994                }
1995
1996                let span = bound.span().find_ancestor_inside(predicate_span)?;
1997                if span.in_external_macro(tcx.sess.source_map()) {
1998                    return None;
1999                }
2000
2001                Some((i, span))
2002            })
2003            .collect()
2004    }
2005
2006    fn consolidate_outlives_bound_spans(
2007        &self,
2008        lo: Span,
2009        bounds: &hir::GenericBounds<'_>,
2010        bound_spans: Vec<(usize, Span)>,
2011    ) -> Vec<Span> {
2012        if bounds.is_empty() {
2013            return Vec::new();
2014        }
2015        if bound_spans.len() == bounds.len() {
2016            let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
2017            // If all bounds are inferable, we want to delete the colon, so
2018            // start from just after the parameter (span passed as argument)
2019            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [lo.to(last_bound_span)]))vec![lo.to(last_bound_span)]
2020        } else {
2021            let mut merged = Vec::new();
2022            let mut last_merged_i = None;
2023
2024            let mut from_start = true;
2025            for (i, bound_span) in bound_spans {
2026                match last_merged_i {
2027                    // If the first bound is inferable, our span should also eat the leading `+`.
2028                    None if i == 0 => {
2029                        merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
2030                        last_merged_i = Some(0);
2031                    }
2032                    // If consecutive bounds are inferable, merge their spans
2033                    Some(h) if i == h + 1 => {
2034                        if let Some(tail) = merged.last_mut() {
2035                            // Also eat the trailing `+` if the first
2036                            // more-than-one bound is inferable
2037                            let to_span = if from_start && i < bounds.len() {
2038                                bounds[i + 1].span().shrink_to_lo()
2039                            } else {
2040                                bound_span
2041                            };
2042                            *tail = tail.to(to_span);
2043                            last_merged_i = Some(i);
2044                        } else {
2045                            ::rustc_middle::util::bug::bug_fmt(format_args!("another bound-span visited earlier"));bug!("another bound-span visited earlier");
2046                        }
2047                    }
2048                    _ => {
2049                        // When we find a non-inferable bound, subsequent inferable bounds
2050                        // won't be consecutive from the start (and we'll eat the leading
2051                        // `+` rather than the trailing one)
2052                        from_start = false;
2053                        merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
2054                        last_merged_i = Some(i);
2055                    }
2056                }
2057            }
2058            merged
2059        }
2060    }
2061}
2062
2063impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements {
2064    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
2065        use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
2066
2067        let def_id = item.owner_id.def_id;
2068        if let hir::ItemKind::Struct(_, generics, _)
2069        | hir::ItemKind::Enum(_, generics, _)
2070        | hir::ItemKind::Union(_, generics, _) = item.kind
2071        {
2072            let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
2073            if inferred_outlives.is_empty() {
2074                return;
2075            }
2076
2077            let ty_generics = cx.tcx.generics_of(def_id);
2078            let num_where_predicates = generics
2079                .predicates
2080                .iter()
2081                .filter(|predicate| predicate.kind.in_where_clause())
2082                .count();
2083
2084            let mut bound_count = 0;
2085            let mut lint_spans = Vec::new();
2086            let mut where_lint_spans = Vec::new();
2087            let mut dropped_where_predicate_count = 0;
2088            for (i, where_predicate) in generics.predicates.iter().enumerate() {
2089                let (relevant_lifetimes, bounds, predicate_span, in_where_clause) =
2090                    match where_predicate.kind {
2091                        hir::WherePredicateKind::RegionPredicate(predicate) => {
2092                            if let Some(ResolvedArg::EarlyBound(region_def_id)) =
2093                                cx.tcx.named_bound_var(predicate.lifetime.hir_id)
2094                            {
2095                                (
2096                                    Self::lifetimes_outliving_lifetime(
2097                                        cx.tcx,
2098                                        // don't warn if the inferred span actually came from the predicate we're looking at
2099                                        // this happens if the type is recursively defined
2100                                        inferred_outlives.iter().filter(|(_, span)| {
2101                                            !where_predicate.span.contains(*span)
2102                                        }),
2103                                        item.owner_id.def_id,
2104                                        region_def_id,
2105                                    ),
2106                                    &predicate.bounds,
2107                                    where_predicate.span,
2108                                    predicate.in_where_clause,
2109                                )
2110                            } else {
2111                                continue;
2112                            }
2113                        }
2114                        hir::WherePredicateKind::BoundPredicate(predicate) => {
2115                            // FIXME we can also infer bounds on associated types,
2116                            // and should check for them here.
2117                            match predicate.bounded_ty.kind {
2118                                hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2119                                    let Res::Def(DefKind::TyParam, def_id) = path.res else {
2120                                        continue;
2121                                    };
2122                                    let index = ty_generics.param_def_id_to_index[&def_id];
2123                                    (
2124                                        Self::lifetimes_outliving_type(
2125                                            // don't warn if the inferred span actually came from the predicate we're looking at
2126                                            // this happens if the type is recursively defined
2127                                            inferred_outlives.iter().filter(|(_, span)| {
2128                                                !where_predicate.span.contains(*span)
2129                                            }),
2130                                            index,
2131                                        ),
2132                                        &predicate.bounds,
2133                                        where_predicate.span,
2134                                        predicate.origin == PredicateOrigin::WhereClause,
2135                                    )
2136                                }
2137                                _ => {
2138                                    continue;
2139                                }
2140                            }
2141                        }
2142                        _ => continue,
2143                    };
2144                if relevant_lifetimes.is_empty() {
2145                    continue;
2146                }
2147
2148                let bound_spans = self.collect_outlives_bound_spans(
2149                    cx.tcx,
2150                    bounds,
2151                    &relevant_lifetimes,
2152                    predicate_span,
2153                    item.owner_id.to_def_id(),
2154                );
2155                bound_count += bound_spans.len();
2156
2157                let drop_predicate = bound_spans.len() == bounds.len();
2158                if drop_predicate && in_where_clause {
2159                    dropped_where_predicate_count += 1;
2160                }
2161
2162                if drop_predicate {
2163                    if !in_where_clause {
2164                        lint_spans.push(predicate_span);
2165                    } else if predicate_span.from_expansion() {
2166                        // Don't try to extend the span if it comes from a macro expansion.
2167                        where_lint_spans.push(predicate_span);
2168                    } else if i + 1 < num_where_predicates {
2169                        // If all the bounds on a predicate were inferable and there are
2170                        // further predicates, we want to eat the trailing comma.
2171                        let next_predicate_span = generics.predicates[i + 1].span;
2172                        if next_predicate_span.from_expansion() {
2173                            where_lint_spans.push(predicate_span);
2174                        } else {
2175                            where_lint_spans
2176                                .push(predicate_span.to(next_predicate_span.shrink_to_lo()));
2177                        }
2178                    } else {
2179                        // Eat the optional trailing comma after the last predicate.
2180                        let where_span = generics.where_clause_span;
2181                        if where_span.from_expansion() {
2182                            where_lint_spans.push(predicate_span);
2183                        } else {
2184                            where_lint_spans.push(predicate_span.to(where_span.shrink_to_hi()));
2185                        }
2186                    }
2187                } else {
2188                    where_lint_spans.extend(self.consolidate_outlives_bound_spans(
2189                        predicate_span.shrink_to_lo(),
2190                        bounds,
2191                        bound_spans,
2192                    ));
2193                }
2194            }
2195
2196            // If all predicates in where clause are inferable, drop the entire clause
2197            // (including the `where`)
2198            if generics.has_where_clause_predicates
2199                && dropped_where_predicate_count == num_where_predicates
2200            {
2201                let where_span = generics.where_clause_span;
2202                // Extend the where clause back to the closing `>` of the
2203                // generics, except for tuple struct, which have the `where`
2204                // after the fields of the struct.
2205                let full_where_span =
2206                    if let hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(..)) = item.kind {
2207                        where_span
2208                    } else {
2209                        generics.span.shrink_to_hi().to(where_span)
2210                    };
2211
2212                // Due to macro expansions, the `full_where_span` might not actually contain all
2213                // predicates.
2214                if where_lint_spans.iter().all(|&sp| full_where_span.contains(sp)) {
2215                    lint_spans.push(full_where_span);
2216                } else {
2217                    lint_spans.extend(where_lint_spans);
2218                }
2219            } else {
2220                lint_spans.extend(where_lint_spans);
2221            }
2222
2223            if !lint_spans.is_empty() {
2224                // Do not automatically delete outlives requirements from macros.
2225                let applicability = if lint_spans.iter().all(|sp| sp.can_be_used_for_suggestions())
2226                {
2227                    Applicability::MachineApplicable
2228                } else {
2229                    Applicability::MaybeIncorrect
2230                };
2231
2232                // Due to macros, there might be several predicates with the same span
2233                // and we only want to suggest removing them once.
2234                lint_spans.sort_unstable();
2235                lint_spans.dedup();
2236
2237                cx.emit_span_lint(
2238                    EXPLICIT_OUTLIVES_REQUIREMENTS,
2239                    lint_spans.clone(),
2240                    BuiltinExplicitOutlives {
2241                        suggestion: BuiltinExplicitOutlivesSuggestion {
2242                            spans: lint_spans,
2243                            applicability,
2244                            count: bound_count,
2245                        },
2246                    },
2247                );
2248            }
2249        }
2250    }
2251}
2252
2253#[doc =
r" The `incomplete_features` lint detects unstable features enabled with"]
#[doc =
r" the [`feature` attribute] that may function improperly in some or all"]
#[doc = r" cases."]
#[doc = r""]
#[doc =
r" [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(generic_const_exprs)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Although it is encouraged for people to experiment with unstable"]
#[doc =
r" features, some of them are known to be incomplete or faulty. This lint"]
#[doc =
r" is a signal that the feature has not yet been finished, and you may"]
#[doc = r" experience problems with it."]
pub static INCOMPLETE_FEATURES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "INCOMPLETE_FEATURES",
            default_level: ::rustc_lint_defs::Warn,
            desc: "incomplete features that may function improperly in some or all cases",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
2254    /// The `incomplete_features` lint detects unstable features enabled with
2255    /// the [`feature` attribute] that may function improperly in some or all
2256    /// cases.
2257    ///
2258    /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/
2259    ///
2260    /// ### Example
2261    ///
2262    /// ```rust
2263    /// #![feature(generic_const_exprs)]
2264    /// ```
2265    ///
2266    /// {{produces}}
2267    ///
2268    /// ### Explanation
2269    ///
2270    /// Although it is encouraged for people to experiment with unstable
2271    /// features, some of them are known to be incomplete or faulty. This lint
2272    /// is a signal that the feature has not yet been finished, and you may
2273    /// experience problems with it.
2274    pub INCOMPLETE_FEATURES,
2275    Warn,
2276    "incomplete features that may function improperly in some or all cases"
2277}
2278
2279#[doc =
r" The `internal_features` lint detects unstable features enabled with"]
#[doc =
r" the [`feature` attribute] that are internal to the compiler or standard"]
#[doc = r" library."]
#[doc = r""]
#[doc =
r" [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(rustc_attrs)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" These features are an implementation detail of the compiler and standard"]
#[doc = r" library and are not supposed to be used in user code."]
pub static INTERNAL_FEATURES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "INTERNAL_FEATURES",
            default_level: ::rustc_lint_defs::Warn,
            desc: "internal features are not supposed to be used",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
2280    /// The `internal_features` lint detects unstable features enabled with
2281    /// the [`feature` attribute] that are internal to the compiler or standard
2282    /// library.
2283    ///
2284    /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/
2285    ///
2286    /// ### Example
2287    ///
2288    /// ```rust
2289    /// #![feature(rustc_attrs)]
2290    /// ```
2291    ///
2292    /// {{produces}}
2293    ///
2294    /// ### Explanation
2295    ///
2296    /// These features are an implementation detail of the compiler and standard
2297    /// library and are not supposed to be used in user code.
2298    pub INTERNAL_FEATURES,
2299    Warn,
2300    "internal features are not supposed to be used"
2301}
2302
2303#[doc =
r" Check for used feature gates in `INCOMPLETE_FEATURES` in `rustc_feature/src/unstable.rs`."]
pub struct IncompleteInternalFeatures;
#[automatically_derived]
impl ::core::marker::Copy for IncompleteInternalFeatures { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IncompleteInternalFeatures { }
#[automatically_derived]
impl ::core::clone::Clone for IncompleteInternalFeatures {
    #[inline]
    fn clone(&self) -> IncompleteInternalFeatures { *self }
}
impl ::rustc_lint_defs::LintPass for IncompleteInternalFeatures {
    fn name(&self) -> &'static str { "IncompleteInternalFeatures" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INCOMPLETE_FEATURES, INTERNAL_FEATURES]))
    }
}
impl IncompleteInternalFeatures {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INCOMPLETE_FEATURES, INTERNAL_FEATURES]))
    }
}declare_lint_pass!(
2304    /// Check for used feature gates in `INCOMPLETE_FEATURES` in `rustc_feature/src/unstable.rs`.
2305    IncompleteInternalFeatures => [INCOMPLETE_FEATURES, INTERNAL_FEATURES]
2306);
2307
2308impl EarlyLintPass for IncompleteInternalFeatures {
2309    fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
2310        let features = cx.builder.features();
2311
2312        features
2313            .enabled_features_iter_stable_order()
2314            .filter(|(name, _)| features.incomplete(*name) || features.internal(*name))
2315            .for_each(|(name, span)| {
2316                if features.incomplete(name) {
2317                    let note = rustc_feature::find_feature_issue(name, GateIssue::Language)
2318                        .map(|n| BuiltinFeatureIssueNote { n });
2319                    let help = HAS_MIN_FEATURES
2320                        .contains(&name)
2321                        .then_some(BuiltinIncompleteFeaturesHelp { name });
2322
2323                    cx.emit_span_lint(
2324                        INCOMPLETE_FEATURES,
2325                        span,
2326                        BuiltinIncompleteFeatures { name, note, help },
2327                    );
2328                } else {
2329                    cx.emit_span_lint(INTERNAL_FEATURES, span, BuiltinInternalFeatures { name });
2330                }
2331            });
2332    }
2333}
2334
2335const HAS_MIN_FEATURES: &[Symbol] = &[sym::specialization];
2336
2337#[doc =
r" The `invalid_value` lint detects creating a value that is not valid,"]
#[doc = r" such as a null reference."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run"]
#[doc = r" # #![allow(unused)]"]
#[doc = r" unsafe {"]
#[doc = r"     let x: &'static i32 = std::mem::zeroed();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" In some situations the compiler can detect that the code is creating"]
#[doc = r" an invalid value, which should be avoided."]
#[doc = r""]
#[doc = r" In particular, this lint will check for improper use of"]
#[doc = r" [`mem::zeroed`], [`mem::uninitialized`], [`mem::transmute`], and"]
#[doc =
r" [`MaybeUninit::assume_init`] that can cause [undefined behavior]. The"]
#[doc =
r" lint should provide extra information to indicate what the problem is"]
#[doc = r" and a possible solution."]
#[doc = r""]
#[doc = r" [`mem::zeroed`]: https://doc.rust-lang.org/std/mem/fn.zeroed.html"]
#[doc =
r" [`mem::uninitialized`]: https://doc.rust-lang.org/std/mem/fn.uninitialized.html"]
#[doc =
r" [`mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html"]
#[doc =
r" [`MaybeUninit::assume_init`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.assume_init"]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
pub static INVALID_VALUE: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "INVALID_VALUE",
            default_level: ::rustc_lint_defs::Warn,
            desc: "an invalid value is being created (such as a null reference)",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
2338    /// The `invalid_value` lint detects creating a value that is not valid,
2339    /// such as a null reference.
2340    ///
2341    /// ### Example
2342    ///
2343    /// ```rust,no_run
2344    /// # #![allow(unused)]
2345    /// unsafe {
2346    ///     let x: &'static i32 = std::mem::zeroed();
2347    /// }
2348    /// ```
2349    ///
2350    /// {{produces}}
2351    ///
2352    /// ### Explanation
2353    ///
2354    /// In some situations the compiler can detect that the code is creating
2355    /// an invalid value, which should be avoided.
2356    ///
2357    /// In particular, this lint will check for improper use of
2358    /// [`mem::zeroed`], [`mem::uninitialized`], [`mem::transmute`], and
2359    /// [`MaybeUninit::assume_init`] that can cause [undefined behavior]. The
2360    /// lint should provide extra information to indicate what the problem is
2361    /// and a possible solution.
2362    ///
2363    /// [`mem::zeroed`]: https://doc.rust-lang.org/std/mem/fn.zeroed.html
2364    /// [`mem::uninitialized`]: https://doc.rust-lang.org/std/mem/fn.uninitialized.html
2365    /// [`mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html
2366    /// [`MaybeUninit::assume_init`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.assume_init
2367    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2368    pub INVALID_VALUE,
2369    Warn,
2370    "an invalid value is being created (such as a null reference)"
2371}
2372
2373pub struct InvalidValue;
#[automatically_derived]
impl ::core::marker::Copy for InvalidValue { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidValue { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidValue {
    #[inline]
    fn clone(&self) -> InvalidValue { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidValue {
    fn name(&self) -> &'static str { "InvalidValue" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INVALID_VALUE]))
    }
}
impl InvalidValue {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INVALID_VALUE]))
    }
}declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
2374
2375/// Information about why a type cannot be initialized this way.
2376pub struct InitError {
2377    pub(crate) message: String,
2378    /// Spans from struct fields and similar that can be obtained from just the type.
2379    pub(crate) span: Option<Span>,
2380    /// Used to report a trace through adts.
2381    pub(crate) nested: Option<Box<InitError>>,
2382}
2383impl InitError {
2384    fn spanned(self, span: Span) -> InitError {
2385        Self { span: Some(span), ..self }
2386    }
2387
2388    fn nested(self, nested: impl Into<Option<InitError>>) -> InitError {
2389        if !self.nested.is_none() {
    ::core::panicking::panic("assertion failed: self.nested.is_none()")
};assert!(self.nested.is_none());
2390        Self { nested: nested.into().map(Box::new), ..self }
2391    }
2392}
2393
2394impl<'a> From<&'a str> for InitError {
2395    fn from(s: &'a str) -> Self {
2396        s.to_owned().into()
2397    }
2398}
2399impl From<String> for InitError {
2400    fn from(message: String) -> Self {
2401        Self { message, span: None, nested: None }
2402    }
2403}
2404
2405impl<'tcx> LateLintPass<'tcx> for InvalidValue {
2406    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2407        #[derive(#[automatically_derived]
impl ::core::fmt::Debug for InitKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                InitKind::Zeroed => "Zeroed",
                InitKind::Uninit => "Uninit",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for InitKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InitKind {
    #[inline]
    fn clone(&self) -> InitKind { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for InitKind {
    #[inline]
    fn eq(&self, other: &InitKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
2408        enum InitKind {
2409            Zeroed,
2410            Uninit,
2411        }
2412
2413        /// Test if this constant is all-0.
2414        fn is_zero(expr: &hir::Expr<'_>) -> bool {
2415            use hir::ExprKind::*;
2416            use rustc_ast::LitKind::*;
2417            match &expr.kind {
2418                Lit(lit) => {
2419                    if let Int(i, _) = lit.node {
2420                        i == 0
2421                    } else {
2422                        false
2423                    }
2424                }
2425                Tup(tup) => tup.iter().all(is_zero),
2426                _ => false,
2427            }
2428        }
2429
2430        /// Determine if this expression is a "dangerous initialization".
2431        fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
2432            if let hir::ExprKind::Call(path_expr, args) = expr.kind
2433                // Find calls to `mem::{uninitialized,zeroed}` methods.
2434                && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2435            {
2436                let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2437                match cx.tcx.get_diagnostic_name(def_id) {
2438                    Some(sym::mem_zeroed) => return Some(InitKind::Zeroed),
2439                    Some(sym::mem_uninitialized) => return Some(InitKind::Uninit),
2440                    Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed),
2441                    _ => {}
2442                }
2443            } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind {
2444                // Find problematic calls to `MaybeUninit::assume_init`.
2445                let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
2446                if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
2447                    // This is a call to *some* method named `assume_init`.
2448                    // See if the `self` parameter is one of the dangerous constructors.
2449                    if let hir::ExprKind::Call(path_expr, _) = receiver.kind
2450                        && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2451                    {
2452                        let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2453                        match cx.tcx.get_diagnostic_name(def_id) {
2454                            Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed),
2455                            Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit),
2456                            _ => {}
2457                        }
2458                    }
2459                }
2460            }
2461
2462            None
2463        }
2464
2465        fn variant_find_init_error<'tcx>(
2466            cx: &LateContext<'tcx>,
2467            ty: Ty<'tcx>,
2468            variant: &VariantDef,
2469            args: ty::GenericArgsRef<'tcx>,
2470            descr: &str,
2471            init: InitKind,
2472        ) -> Option<InitError> {
2473            let mut field_err = variant.fields.iter().find_map(|field| {
2474                ty_find_init_error(cx, field.ty(cx.tcx, args), init).map(|mut err| {
2475                    if !field.did.is_local() {
2476                        err
2477                    } else if err.span.is_none() {
2478                        err.span = Some(cx.tcx.def_span(field.did));
2479                        (&mut err.message).write_fmt(format_args!(" (in this {0})", descr))write!(&mut err.message, " (in this {descr})").unwrap();
2480                        err
2481                    } else {
2482                        InitError::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in this {0}", descr))
    })format!("in this {descr}"))
2483                            .spanned(cx.tcx.def_span(field.did))
2484                            .nested(err)
2485                    }
2486                })
2487            });
2488
2489            // Check if this ADT has a constrained layout (like `NonNull` and friends).
2490            if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(ty)) {
2491                if let BackendRepr::Scalar(scalar) | BackendRepr::ScalarPair(scalar, _) =
2492                    &layout.backend_repr
2493                {
2494                    let range = scalar.valid_range(cx);
2495                    let msg = if !range.contains(0) {
2496                        "must be non-null"
2497                    } else if init == InitKind::Uninit && !scalar.is_always_valid(cx) {
2498                        // Prefer reporting on the fields over the entire struct for uninit,
2499                        // as the information bubbles out and it may be unclear why the type can't
2500                        // be null from just its outside signature.
2501
2502                        "must be initialized inside its custom valid range"
2503                    } else {
2504                        return field_err;
2505                    };
2506                    if let Some(field_err) = &mut field_err {
2507                        // Most of the time, if the field error is the same as the struct error,
2508                        // the struct error only happens because of the field error.
2509                        if field_err.message.contains(msg) {
2510                            field_err.message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("because {0}", field_err.message))
    })format!("because {}", field_err.message);
2511                        }
2512                    }
2513                    return Some(InitError::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` {1}", ty, msg))
    })format!("`{ty}` {msg}")).nested(field_err));
2514                }
2515            }
2516            field_err
2517        }
2518
2519        /// Return `Some` only if we are sure this type does *not*
2520        /// allow zero initialization.
2521        fn ty_find_init_error<'tcx>(
2522            cx: &LateContext<'tcx>,
2523            ty: Ty<'tcx>,
2524            init: InitKind,
2525        ) -> Option<InitError> {
2526            let ty = cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty);
2527
2528            match ty.kind() {
2529                // Primitive types that don't like 0 as a value.
2530                ty::Ref(..) => Some("references must be non-null".into()),
2531                ty::Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()),
2532                ty::FnPtr(..) => Some("function pointers must be non-null".into()),
2533                ty::Never => Some("the `!` type has no valid value".into()),
2534                ty::RawPtr(ty, _) if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Dynamic(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Dynamic(..)) =>
2535                // raw ptr to dyn Trait
2536                {
2537                    Some("the vtable of a wide raw pointer must be non-null".into())
2538                }
2539                // Primitive types with other constraints.
2540                ty::Bool if init == InitKind::Uninit => {
2541                    Some("booleans must be either `true` or `false`".into())
2542                }
2543                ty::Char if init == InitKind::Uninit => {
2544                    Some("characters must be a valid Unicode codepoint".into())
2545                }
2546                ty::Int(_) | ty::Uint(_) if init == InitKind::Uninit => {
2547                    Some("integers must be initialized".into())
2548                }
2549                ty::Float(_) if init == InitKind::Uninit => {
2550                    Some("floats must be initialized".into())
2551                }
2552                ty::RawPtr(_, _) if init == InitKind::Uninit => {
2553                    Some("raw pointers must be initialized".into())
2554                }
2555                // Recurse and checks for some compound types. (but not unions)
2556                ty::Adt(adt_def, args) if !adt_def.is_union() => {
2557                    // Handle structs.
2558                    if adt_def.is_struct() {
2559                        return variant_find_init_error(
2560                            cx,
2561                            ty,
2562                            adt_def.non_enum_variant(),
2563                            args,
2564                            "struct field",
2565                            init,
2566                        );
2567                    }
2568                    // And now, enums.
2569                    let span = cx.tcx.def_span(adt_def.did());
2570                    let mut potential_variants = adt_def.variants().iter().filter_map(|variant| {
2571                        let definitely_inhabited = match variant
2572                            .inhabited_predicate(cx.tcx, *adt_def)
2573                            .instantiate(cx.tcx, args)
2574                            .apply_any_module(cx.tcx, cx.typing_env())
2575                        {
2576                            // Entirely skip uninhabited variants.
2577                            Some(false) => return None,
2578                            // Forward the others, but remember which ones are definitely inhabited.
2579                            Some(true) => true,
2580                            None => false,
2581                        };
2582                        Some((variant, definitely_inhabited))
2583                    });
2584                    let Some(first_variant) = potential_variants.next() else {
2585                        return Some(
2586                            InitError::from("enums with no inhabited variants have no valid value")
2587                                .spanned(span),
2588                        );
2589                    };
2590                    // So we have at least one potentially inhabited variant. Might we have two?
2591                    let Some(second_variant) = potential_variants.next() else {
2592                        // There is only one potentially inhabited variant. So we can recursively
2593                        // check that variant!
2594                        return variant_find_init_error(
2595                            cx,
2596                            ty,
2597                            first_variant.0,
2598                            args,
2599                            "field of the only potentially inhabited enum variant",
2600                            init,
2601                        );
2602                    };
2603                    // So we have at least two potentially inhabited variants. If we can prove that
2604                    // we have at least two *definitely* inhabited variants, then we have a tag and
2605                    // hence leaving this uninit is definitely disallowed. (Leaving it zeroed could
2606                    // be okay, depending on which variant is encoded as zero tag.)
2607                    if init == InitKind::Uninit {
2608                        let definitely_inhabited = (first_variant.1 as usize)
2609                            + (second_variant.1 as usize)
2610                            + potential_variants
2611                                .filter(|(_variant, definitely_inhabited)| *definitely_inhabited)
2612                                .count();
2613                        if definitely_inhabited > 1 {
2614                            return Some(InitError::from(
2615                                "enums with multiple inhabited variants have to be initialized to a variant",
2616                            ).spanned(span));
2617                        }
2618                    }
2619                    // We couldn't find anything wrong here.
2620                    None
2621                }
2622                ty::Tuple(..) => {
2623                    // Proceed recursively, check all fields.
2624                    ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init))
2625                }
2626                ty::Array(ty, len) => {
2627                    if #[allow(non_exhaustive_omitted_patterns)] match len.try_to_target_usize(cx.tcx)
    {
    Some(v) if v > 0 => true,
    _ => false,
}matches!(len.try_to_target_usize(cx.tcx), Some(v) if v > 0) {
2628                        // Array length known at array non-empty -- recurse.
2629                        ty_find_init_error(cx, *ty, init)
2630                    } else {
2631                        // Empty array or size unknown.
2632                        None
2633                    }
2634                }
2635                // Conservative fallback.
2636                _ => None,
2637            }
2638        }
2639
2640        if let Some(init) = is_dangerous_init(cx, expr) {
2641            // This conjures an instance of a type out of nothing,
2642            // using zeroed or uninitialized memory.
2643            // We are extremely conservative with what we warn about.
2644            let conjured_ty = cx.typeck_results().expr_ty(expr);
2645            if let Some(err) = {
    let _guard = NoTrimmedGuard::new();
    ty_find_init_error(cx, conjured_ty, init)
}with_no_trimmed_paths!(ty_find_init_error(cx, conjured_ty, init)) {
2646                let msg = match init {
2647                    InitKind::Zeroed => {
2648                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the type `{$ty}` does not permit zero-initialization"))msg!("the type `{$ty}` does not permit zero-initialization")
2649                    }
2650                    InitKind::Uninit => {
2651                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the type `{$ty}` does not permit being left uninitialized"))msg!("the type `{$ty}` does not permit being left uninitialized")
2652                    }
2653                };
2654                let sub = BuiltinUnpermittedTypeInitSub { err };
2655                cx.emit_span_lint(
2656                    INVALID_VALUE,
2657                    expr.span,
2658                    BuiltinUnpermittedTypeInit {
2659                        msg,
2660                        ty: conjured_ty,
2661                        label: expr.span,
2662                        sub,
2663                        tcx: cx.tcx,
2664                    },
2665                );
2666            }
2667        }
2668    }
2669}
2670
2671#[doc =
r" The `deref_nullptr` lint detects when a null pointer is dereferenced,"]
#[doc = r" which causes [undefined behavior]."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # #![allow(unused)]"]
#[doc = r" use std::ptr;"]
#[doc = r" unsafe {"]
#[doc = r"     let x = &*ptr::null::<i32>();"]
#[doc = r"     let x = ptr::addr_of!(*ptr::null::<i32>());"]
#[doc = r"     let x = *(0 as *const i32);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Dereferencing a null pointer causes [undefined behavior] if it is accessed"]
#[doc = r" (loaded from or stored to)."]
#[doc = r""]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
pub static DEREF_NULLPTR: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "DEREF_NULLPTR",
            default_level: ::rustc_lint_defs::Deny,
            desc: "detects when an null pointer is dereferenced",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
2672    /// The `deref_nullptr` lint detects when a null pointer is dereferenced,
2673    /// which causes [undefined behavior].
2674    ///
2675    /// ### Example
2676    ///
2677    /// ```rust,compile_fail
2678    /// # #![allow(unused)]
2679    /// use std::ptr;
2680    /// unsafe {
2681    ///     let x = &*ptr::null::<i32>();
2682    ///     let x = ptr::addr_of!(*ptr::null::<i32>());
2683    ///     let x = *(0 as *const i32);
2684    /// }
2685    /// ```
2686    ///
2687    /// {{produces}}
2688    ///
2689    /// ### Explanation
2690    ///
2691    /// Dereferencing a null pointer causes [undefined behavior] if it is accessed
2692    /// (loaded from or stored to).
2693    ///
2694    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2695    pub DEREF_NULLPTR,
2696    Deny,
2697    "detects when an null pointer is dereferenced"
2698}
2699
2700pub struct DerefNullPtr;
#[automatically_derived]
impl ::core::marker::Copy for DerefNullPtr { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DerefNullPtr { }
#[automatically_derived]
impl ::core::clone::Clone for DerefNullPtr {
    #[inline]
    fn clone(&self) -> DerefNullPtr { *self }
}
impl ::rustc_lint_defs::LintPass for DerefNullPtr {
    fn name(&self) -> &'static str { "DerefNullPtr" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DEREF_NULLPTR]))
    }
}
impl DerefNullPtr {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DEREF_NULLPTR]))
    }
}declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]);
2701
2702impl<'tcx> LateLintPass<'tcx> for DerefNullPtr {
2703    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2704        /// test if expression is a null ptr
2705        fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
2706            let pointer_ty = cx.typeck_results().expr_ty(expr);
2707            let ty::RawPtr(pointee, _) = pointer_ty.kind() else {
2708                return false;
2709            };
2710            if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(*pointee)) {
2711                if layout.layout.size() == rustc_abi::Size::ZERO {
2712                    return false;
2713                }
2714            }
2715
2716            match &expr.kind {
2717                hir::ExprKind::Cast(expr, ty) => {
2718                    if let hir::TyKind::Ptr(_) = ty.kind {
2719                        return is_zero(expr) || is_null_ptr(cx, expr);
2720                    }
2721                }
2722                // check for call to `core::ptr::null` or `core::ptr::null_mut`
2723                hir::ExprKind::Call(path, _) => {
2724                    if let hir::ExprKind::Path(ref qpath) = path.kind
2725                        && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
2726                    {
2727                        return #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
    {
    Some(sym::ptr_null | sym::ptr_null_mut) => true,
    _ => false,
}matches!(
2728                            cx.tcx.get_diagnostic_name(def_id),
2729                            Some(sym::ptr_null | sym::ptr_null_mut)
2730                        );
2731                    }
2732                }
2733                _ => {}
2734            }
2735            false
2736        }
2737
2738        /// test if expression is the literal `0`
2739        fn is_zero(expr: &hir::Expr<'_>) -> bool {
2740            match &expr.kind {
2741                hir::ExprKind::Lit(lit) => {
2742                    if let LitKind::Int(a, _) = lit.node {
2743                        return a == 0;
2744                    }
2745                }
2746                _ => {}
2747            }
2748            false
2749        }
2750
2751        if let hir::ExprKind::Unary(hir::UnOp::Deref, expr_deref) = expr.kind
2752            && is_null_ptr(cx, expr_deref)
2753        {
2754            if let hir::Node::Expr(hir::Expr {
2755                kind: hir::ExprKind::AddrOf(hir::BorrowKind::Raw, ..),
2756                ..
2757            }) = cx.tcx.parent_hir_node(expr.hir_id)
2758            {
2759                // `&raw *NULL` is ok.
2760            } else {
2761                cx.emit_span_lint(
2762                    DEREF_NULLPTR,
2763                    expr.span,
2764                    BuiltinDerefNullptr { label: expr.span },
2765                );
2766            }
2767        }
2768    }
2769}
2770
2771#[doc =
r" The `named_asm_labels` lint detects the use of named labels in the"]
#[doc = r" inline `asm!` macro."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # #![feature(asm_experimental_arch)]"]
#[doc = r" use std::arch::asm;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     unsafe {"]
#[doc = r#"         asm!("foo: bar");"#]
#[doc = r"     }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" LLVM is allowed to duplicate inline assembly blocks for any"]
#[doc =
r" reason, for example when it is in a function that gets inlined. Because"]
#[doc =
r" of this, GNU assembler [local labels] *must* be used instead of labels"]
#[doc =
r" with a name. Using named labels might cause assembler or linker errors."]
#[doc = r""]
#[doc = r" See the explanation in [Rust By Example] for more details."]
#[doc = r""]
#[doc =
r" [local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels"]
#[doc =
r" [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels"]
pub static NAMED_ASM_LABELS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NAMED_ASM_LABELS",
            default_level: ::rustc_lint_defs::Deny,
            desc: "named labels in inline assembly",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
2772    /// The `named_asm_labels` lint detects the use of named labels in the
2773    /// inline `asm!` macro.
2774    ///
2775    /// ### Example
2776    ///
2777    /// ```rust,compile_fail
2778    /// # #![feature(asm_experimental_arch)]
2779    /// use std::arch::asm;
2780    ///
2781    /// fn main() {
2782    ///     unsafe {
2783    ///         asm!("foo: bar");
2784    ///     }
2785    /// }
2786    /// ```
2787    ///
2788    /// {{produces}}
2789    ///
2790    /// ### Explanation
2791    ///
2792    /// LLVM is allowed to duplicate inline assembly blocks for any
2793    /// reason, for example when it is in a function that gets inlined. Because
2794    /// of this, GNU assembler [local labels] *must* be used instead of labels
2795    /// with a name. Using named labels might cause assembler or linker errors.
2796    ///
2797    /// See the explanation in [Rust By Example] for more details.
2798    ///
2799    /// [local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels
2800    /// [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels
2801    pub NAMED_ASM_LABELS,
2802    Deny,
2803    "named labels in inline assembly",
2804}
2805
2806#[doc =
r" The `binary_asm_labels` lint detects the use of numeric labels containing only binary"]
#[doc = r" digits in the inline `asm!` macro."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,ignore (fails on non-x86_64)"]
#[doc = r#" #![cfg(target_arch = "x86_64")]"#]
#[doc = r""]
#[doc = r" use std::arch::asm;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     unsafe {"]
#[doc = r#"         asm!("0: jmp 0b");"#]
#[doc = r"     }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" This will produce:"]
#[doc = r""]
#[doc = r" ```text"]
#[doc =
r" error: avoid using labels containing only the digits `0` and `1` in inline assembly"]
#[doc = r"  --> <source>:7:15"]
#[doc = r"   |"]
#[doc = r#" 7 |         asm!("0: jmp 0b");"#]
#[doc =
r"   |               ^ use a different label that doesn't start with `0` or `1`"]
#[doc = r"   |"]
#[doc = r"   = help: start numbering with `2` instead"]
#[doc =
r"   = note: an LLVM bug makes these labels ambiguous with a binary literal number on x86"]
#[doc =
r"   = note: see <https://github.com/llvm/llvm-project/issues/99547> for more information"]
#[doc = r"   = note: `#[deny(binary_asm_labels)]` on by default"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" An [LLVM bug] causes this code to fail to compile because it interprets the `0b` as a binary"]
#[doc =
r" literal instead of a reference to the previous local label `0`. To work around this bug,"]
#[doc = r" don't use labels that could be confused with a binary literal."]
#[doc = r""]
#[doc = r" This behavior is platform-specific to x86 and x86-64."]
#[doc = r""]
#[doc = r" See the explanation in [Rust By Example] for more details."]
#[doc = r""]
#[doc = r" [LLVM bug]: https://github.com/llvm/llvm-project/issues/99547"]
#[doc =
r" [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels"]
pub static BINARY_ASM_LABELS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "BINARY_ASM_LABELS",
            default_level: ::rustc_lint_defs::Deny,
            desc: "labels in inline assembly containing only 0 or 1 digits",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
2807    /// The `binary_asm_labels` lint detects the use of numeric labels containing only binary
2808    /// digits in the inline `asm!` macro.
2809    ///
2810    /// ### Example
2811    ///
2812    /// ```rust,ignore (fails on non-x86_64)
2813    /// #![cfg(target_arch = "x86_64")]
2814    ///
2815    /// use std::arch::asm;
2816    ///
2817    /// fn main() {
2818    ///     unsafe {
2819    ///         asm!("0: jmp 0b");
2820    ///     }
2821    /// }
2822    /// ```
2823    ///
2824    /// This will produce:
2825    ///
2826    /// ```text
2827    /// error: avoid using labels containing only the digits `0` and `1` in inline assembly
2828    ///  --> <source>:7:15
2829    ///   |
2830    /// 7 |         asm!("0: jmp 0b");
2831    ///   |               ^ use a different label that doesn't start with `0` or `1`
2832    ///   |
2833    ///   = help: start numbering with `2` instead
2834    ///   = note: an LLVM bug makes these labels ambiguous with a binary literal number on x86
2835    ///   = note: see <https://github.com/llvm/llvm-project/issues/99547> for more information
2836    ///   = note: `#[deny(binary_asm_labels)]` on by default
2837    /// ```
2838    ///
2839    /// ### Explanation
2840    ///
2841    /// An [LLVM bug] causes this code to fail to compile because it interprets the `0b` as a binary
2842    /// literal instead of a reference to the previous local label `0`. To work around this bug,
2843    /// don't use labels that could be confused with a binary literal.
2844    ///
2845    /// This behavior is platform-specific to x86 and x86-64.
2846    ///
2847    /// See the explanation in [Rust By Example] for more details.
2848    ///
2849    /// [LLVM bug]: https://github.com/llvm/llvm-project/issues/99547
2850    /// [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels
2851    pub BINARY_ASM_LABELS,
2852    Deny,
2853    "labels in inline assembly containing only 0 or 1 digits",
2854}
2855
2856pub struct AsmLabels;
#[automatically_derived]
impl ::core::marker::Copy for AsmLabels { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AsmLabels { }
#[automatically_derived]
impl ::core::clone::Clone for AsmLabels {
    #[inline]
    fn clone(&self) -> AsmLabels { *self }
}
impl ::rustc_lint_defs::LintPass for AsmLabels {
    fn name(&self) -> &'static str { "AsmLabels" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NAMED_ASM_LABELS, BINARY_ASM_LABELS]))
    }
}
impl AsmLabels {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NAMED_ASM_LABELS, BINARY_ASM_LABELS]))
    }
}declare_lint_pass!(AsmLabels => [NAMED_ASM_LABELS, BINARY_ASM_LABELS]);
2857
2858#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AsmLabelKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AsmLabelKind::Named => "Named",
                AsmLabelKind::FormatArg => "FormatArg",
                AsmLabelKind::Binary => "Binary",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for AsmLabelKind {
    #[inline]
    fn clone(&self) -> AsmLabelKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AsmLabelKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AsmLabelKind {
    #[inline]
    fn eq(&self, other: &AsmLabelKind) -> 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 AsmLabelKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
2859enum AsmLabelKind {
2860    Named,
2861    FormatArg,
2862    Binary,
2863}
2864
2865/// Checks if a potential label is actually a Hexagon register span notation.
2866///
2867/// Hexagon assembly uses register span notation like `r1:0`, `V5:4.w`, `p1:0` etc.
2868/// These follow the pattern: `[letter][digit(s)]:[digit(s)][optional_suffix]`
2869///
2870/// Returns `true` if the string matches a valid Hexagon register span pattern.
2871pub fn is_hexagon_register_span(possible_label: &str) -> bool {
2872    // Extract the full register span from the context
2873    if let Some(colon_idx) = possible_label.find(':') {
2874        let after_colon = &possible_label[colon_idx + 1..];
2875        is_hexagon_register_span_impl(&possible_label[..colon_idx], after_colon)
2876    } else {
2877        false
2878    }
2879}
2880
2881/// Helper function for use within the lint when we have statement context.
2882fn is_hexagon_register_span_context(
2883    possible_label: &str,
2884    statement: &str,
2885    colon_idx: usize,
2886) -> bool {
2887    // Extract what comes after the colon in the statement
2888    let after_colon_start = colon_idx + 1;
2889    if after_colon_start >= statement.len() {
2890        return false;
2891    }
2892
2893    // Get the part after the colon, up to the next whitespace or special character
2894    let after_colon_full = &statement[after_colon_start..];
2895    let after_colon = after_colon_full
2896        .chars()
2897        .take_while(|&c| c.is_ascii_alphanumeric() || c == '.')
2898        .collect::<String>();
2899
2900    is_hexagon_register_span_impl(possible_label, &after_colon)
2901}
2902
2903/// Core implementation for checking hexagon register spans.
2904fn is_hexagon_register_span_impl(before_colon: &str, after_colon: &str) -> bool {
2905    if before_colon.len() < 1 || after_colon.is_empty() {
2906        return false;
2907    }
2908
2909    let mut chars = before_colon.chars();
2910    let start = chars.next().unwrap();
2911
2912    // Must start with a letter (r, V, p, etc.)
2913    if !start.is_ascii_alphabetic() {
2914        return false;
2915    }
2916
2917    let rest = &before_colon[1..];
2918
2919    // Check if the part after the first letter is all digits and non-empty
2920    if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_digit()) {
2921        return false;
2922    }
2923
2924    // Check if after colon starts with digits (may have suffix like .w, .h)
2925    let digits_after = after_colon.chars().take_while(|c| c.is_ascii_digit()).collect::<String>();
2926
2927    !digits_after.is_empty()
2928}
2929
2930impl<'tcx> LateLintPass<'tcx> for AsmLabels {
2931    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
2932        if let hir::Expr {
2933            kind:
2934                hir::ExprKind::InlineAsm(hir::InlineAsm {
2935                    asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
2936                    template_strs,
2937                    options,
2938                    ..
2939                }),
2940            ..
2941        } = expr
2942        {
2943            // Non-generic naked functions are allowed to define arbitrary
2944            // labels.
2945            if *asm_macro == AsmMacro::NakedAsm {
2946                let def_id = expr.hir_id.owner.def_id;
2947                if !cx.tcx.generics_of(def_id).requires_monomorphization(cx.tcx) {
2948                    return;
2949                }
2950            }
2951
2952            // asm with `options(raw)` does not do replacement with `{` and `}`.
2953            let raw = options.contains(InlineAsmOptions::RAW);
2954
2955            for (template_sym, template_snippet, template_span) in template_strs.iter() {
2956                let template_str = template_sym.as_str();
2957                let find_label_span = |needle: &str| -> Option<Span> {
2958                    if let Some(template_snippet) = template_snippet {
2959                        let snippet = template_snippet.as_str();
2960                        if let Some(pos) = snippet.find(needle) {
2961                            let end = pos
2962                                + snippet[pos..]
2963                                    .find(|c| c == ':')
2964                                    .unwrap_or(snippet[pos..].len() - 1);
2965                            let inner = InnerSpan::new(pos, end);
2966                            return Some(template_span.from_inner(inner));
2967                        }
2968                    }
2969
2970                    None
2971                };
2972
2973                // diagnostics are emitted per-template, so this is created here as opposed to the outer loop
2974                let mut spans = Vec::new();
2975
2976                // A semicolon might not actually be specified as a separator for all targets, but
2977                // it seems like LLVM accepts it always.
2978                let statements = template_str.split(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '\n' | ';' => true,
    _ => false,
}matches!(c, '\n' | ';'));
2979                for statement in statements {
2980                    // If there's a comment, trim it from the statement
2981                    let statement = statement.find("//").map_or(statement, |idx| &statement[..idx]);
2982
2983                    // In this loop, if there is ever a non-label, no labels can come after it.
2984                    let mut start_idx = 0;
2985                    'label_loop: for (idx, _) in statement.match_indices(':') {
2986                        let possible_label = statement[start_idx..idx].trim();
2987                        let mut chars = possible_label.chars();
2988
2989                        let Some(start) = chars.next() else {
2990                            // Empty string means a leading ':' in this section, which is not a
2991                            // label.
2992                            break 'label_loop;
2993                        };
2994
2995                        // Whether a { bracket has been seen and its } hasn't been found yet.
2996                        let mut in_bracket = false;
2997                        let mut label_kind = AsmLabelKind::Named;
2998
2999                        // A label can also start with a format arg, if it's not a raw asm block.
3000                        if !raw && start == '{' {
3001                            in_bracket = true;
3002                            label_kind = AsmLabelKind::FormatArg;
3003                        } else if #[allow(non_exhaustive_omitted_patterns)] match start {
    '0' | '1' => true,
    _ => false,
}matches!(start, '0' | '1') {
3004                            // Binary labels have only the characters `0` or `1`.
3005                            label_kind = AsmLabelKind::Binary;
3006                        } else if !(start.is_ascii_alphabetic() || #[allow(non_exhaustive_omitted_patterns)] match start {
    '.' | '_' => true,
    _ => false,
}matches!(start, '.' | '_')) {
3007                            // Named labels start with ASCII letters, `.` or `_`.
3008                            // anything else is not a label
3009                            break 'label_loop;
3010                        }
3011
3012                        // Check for Hexagon register span notation (e.g., "r1:0", "V5:4", "V3:2.w")
3013                        // This is valid Hexagon assembly syntax, not a label
3014                        if #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.sess.asm_arch {
    Some(InlineAsmArch::Hexagon) => true,
    _ => false,
}matches!(cx.tcx.sess.asm_arch, Some(InlineAsmArch::Hexagon))
3015                            && is_hexagon_register_span_context(possible_label, statement, idx)
3016                        {
3017                            break 'label_loop;
3018                        }
3019
3020                        for c in chars {
3021                            // Inside a template format arg, any character is permitted for the
3022                            // purposes of label detection because we assume that it can be
3023                            // replaced with some other valid label string later. `options(raw)`
3024                            // asm blocks cannot have format args, so they are excluded from this
3025                            // special case.
3026                            if !raw && in_bracket {
3027                                if c == '{' {
3028                                    // Nested brackets are not allowed in format args, this cannot
3029                                    // be a label.
3030                                    break 'label_loop;
3031                                }
3032
3033                                if c == '}' {
3034                                    // The end of the format arg.
3035                                    in_bracket = false;
3036                                }
3037                            } else if !raw && c == '{' {
3038                                // Start of a format arg.
3039                                in_bracket = true;
3040                                label_kind = AsmLabelKind::FormatArg;
3041                            } else {
3042                                let can_continue = match label_kind {
3043                                    // Format arg labels are considered to be named labels for the purposes
3044                                    // of continuing outside of their {} pair.
3045                                    AsmLabelKind::Named | AsmLabelKind::FormatArg => {
3046                                        c.is_ascii_alphanumeric() || #[allow(non_exhaustive_omitted_patterns)] match c {
    '_' | '$' => true,
    _ => false,
}matches!(c, '_' | '$')
3047                                    }
3048                                    AsmLabelKind::Binary => #[allow(non_exhaustive_omitted_patterns)] match c {
    '0' | '1' => true,
    _ => false,
}matches!(c, '0' | '1'),
3049                                };
3050
3051                                if !can_continue {
3052                                    // The potential label had an invalid character inside it, it
3053                                    // cannot be a label.
3054                                    break 'label_loop;
3055                                }
3056                            }
3057                        }
3058
3059                        // If all characters passed the label checks, this is a label.
3060                        spans.push((find_label_span(possible_label), label_kind));
3061                        start_idx = idx + 1;
3062                    }
3063                }
3064
3065                for (span, label_kind) in spans {
3066                    let missing_precise_span = span.is_none();
3067                    let span = span.unwrap_or(*template_span);
3068                    match label_kind {
3069                        AsmLabelKind::Named => {
3070                            cx.emit_span_lint(
3071                                NAMED_ASM_LABELS,
3072                                span,
3073                                InvalidAsmLabel::Named { missing_precise_span },
3074                            );
3075                        }
3076                        AsmLabelKind::FormatArg => {
3077                            cx.emit_span_lint(
3078                                NAMED_ASM_LABELS,
3079                                span,
3080                                InvalidAsmLabel::FormatArg { missing_precise_span },
3081                            );
3082                        }
3083                        // the binary asm issue only occurs when using intel syntax on x86 targets
3084                        AsmLabelKind::Binary
3085                            if !options.contains(InlineAsmOptions::ATT_SYNTAX)
3086                                && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.sess.asm_arch {
    Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None => true,
    _ => false,
}matches!(
3087                                    cx.tcx.sess.asm_arch,
3088                                    Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None
3089                                ) =>
3090                        {
3091                            cx.emit_span_lint(
3092                                BINARY_ASM_LABELS,
3093                                span,
3094                                InvalidAsmLabel::Binary { missing_precise_span, span },
3095                            )
3096                        }
3097                        // No lint on anything other than x86
3098                        AsmLabelKind::Binary => (),
3099                    };
3100                }
3101            }
3102        }
3103    }
3104}
3105
3106#[doc = r" The `special_module_name` lint detects module"]
#[doc = r" declarations for files that have a special meaning."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" mod lib;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r"     lib::run();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Cargo recognizes `lib.rs` and `main.rs` as the root of a"]
#[doc = r" library or binary crate, so declaring them as modules"]
#[doc = r" will lead to miscompilation of the crate unless configured"]
#[doc = r" explicitly."]
#[doc = r""]
#[doc = r" To access a library from a binary target within the same crate,"]
#[doc = r" use `your_crate_name::` as the path instead of `lib::`:"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" // bar/src/lib.rs"]
#[doc = r" fn run() {"]
#[doc = r"     // ..."]
#[doc = r" }"]
#[doc = r""]
#[doc = r" // bar/src/main.rs"]
#[doc = r" fn main() {"]
#[doc = r"     bar::run();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" Binary targets cannot be used as libraries and so declaring"]
#[doc = r" one as a module is not allowed."]
pub static SPECIAL_MODULE_NAME: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "SPECIAL_MODULE_NAME",
            default_level: ::rustc_lint_defs::Warn,
            desc: "module declarations for files with a special meaning",
            is_externally_loaded: false,
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
3107    /// The `special_module_name` lint detects module
3108    /// declarations for files that have a special meaning.
3109    ///
3110    /// ### Example
3111    ///
3112    /// ```rust,compile_fail
3113    /// mod lib;
3114    ///
3115    /// fn main() {
3116    ///     lib::run();
3117    /// }
3118    /// ```
3119    ///
3120    /// {{produces}}
3121    ///
3122    /// ### Explanation
3123    ///
3124    /// Cargo recognizes `lib.rs` and `main.rs` as the root of a
3125    /// library or binary crate, so declaring them as modules
3126    /// will lead to miscompilation of the crate unless configured
3127    /// explicitly.
3128    ///
3129    /// To access a library from a binary target within the same crate,
3130    /// use `your_crate_name::` as the path instead of `lib::`:
3131    ///
3132    /// ```rust,compile_fail
3133    /// // bar/src/lib.rs
3134    /// fn run() {
3135    ///     // ...
3136    /// }
3137    ///
3138    /// // bar/src/main.rs
3139    /// fn main() {
3140    ///     bar::run();
3141    /// }
3142    /// ```
3143    ///
3144    /// Binary targets cannot be used as libraries and so declaring
3145    /// one as a module is not allowed.
3146    pub SPECIAL_MODULE_NAME,
3147    Warn,
3148    "module declarations for files with a special meaning",
3149}
3150
3151pub struct SpecialModuleName;
#[automatically_derived]
impl ::core::marker::Copy for SpecialModuleName { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SpecialModuleName { }
#[automatically_derived]
impl ::core::clone::Clone for SpecialModuleName {
    #[inline]
    fn clone(&self) -> SpecialModuleName { *self }
}
impl ::rustc_lint_defs::LintPass for SpecialModuleName {
    fn name(&self) -> &'static str { "SpecialModuleName" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [SPECIAL_MODULE_NAME]))
    }
}
impl SpecialModuleName {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [SPECIAL_MODULE_NAME]))
    }
}declare_lint_pass!(SpecialModuleName => [SPECIAL_MODULE_NAME]);
3152
3153impl EarlyLintPass for SpecialModuleName {
3154    fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
3155        for item in &krate.items {
3156            if let ast::ItemKind::Mod(
3157                _,
3158                ident,
3159                ast::ModKind::Unloaded | ast::ModKind::Loaded(_, ast::Inline::No { .. }, _),
3160            ) = item.kind
3161            {
3162                if item.attrs.iter().any(|a| a.has_name(sym::path)) {
3163                    continue;
3164                }
3165
3166                match ident.name.as_str() {
3167                    "lib" => cx.emit_span_lint(
3168                        SPECIAL_MODULE_NAME,
3169                        item.span,
3170                        BuiltinSpecialModuleNameUsed::Lib,
3171                    ),
3172                    "main" => cx.emit_span_lint(
3173                        SPECIAL_MODULE_NAME,
3174                        item.span,
3175                        BuiltinSpecialModuleNameUsed::Main,
3176                    ),
3177                    _ => continue,
3178                }
3179            }
3180        }
3181    }
3182}
3183
3184#[doc = r" The `internal_eq_trait_method_impls` lint detects manual"]
#[doc = r" implementations of `Eq::assert_receiver_is_total_eq`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #[derive(PartialEq)]"]
#[doc = r" pub struct Foo;"]
#[doc = r""]
#[doc = r" impl Eq for Foo {"]
#[doc = r"     fn assert_receiver_is_total_eq(&self) {}"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" This method existed so that `#[derive(Eq)]` could check that all"]
#[doc = r" fields of a type implement `Eq`. Other users were never supposed"]
#[doc = r" to implement it and it was hidden from documentation."]
#[doc = r""]
#[doc = r" Unfortunately, it was not explicitly marked as unstable and some"]
#[doc =
r" people have now mistakenly assumed they had to implement this method."]
#[doc = r""]
#[doc =
r" As the method is never called by the standard library, you can safely"]
#[doc =
r" remove any implementations of the method and just write `impl Eq for Foo {}`."]
#[doc = r""]
#[doc = r" This is a [future-incompatible] lint to transition this to a hard"]
#[doc = r" error in the future. See [issue #152336] for more details."]
#[doc = r""]
#[doc = r" [issue #152336]: https://github.com/rust-lang/rust/issues/152336"]
pub static INTERNAL_EQ_TRAIT_METHOD_IMPLS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "INTERNAL_EQ_TRAIT_METHOD_IMPLS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "manual implementation of the internal `Eq::assert_receiver_is_total_eq` method",
            is_externally_loaded: false,
            future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
                    reason: ::rustc_lint_defs::FutureIncompatibilityReason::FutureReleaseError(::rustc_lint_defs::ReleaseFcw {
                            issue_number: 152336,
                        }),
                    report_in_deps: false,
                    ..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
                }),
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
3185    /// The `internal_eq_trait_method_impls` lint detects manual
3186    /// implementations of `Eq::assert_receiver_is_total_eq`.
3187    ///
3188    /// ### Example
3189    ///
3190    /// ```rust
3191    /// #[derive(PartialEq)]
3192    /// pub struct Foo;
3193    ///
3194    /// impl Eq for Foo {
3195    ///     fn assert_receiver_is_total_eq(&self) {}
3196    /// }
3197    /// ```
3198    ///
3199    /// {{produces}}
3200    ///
3201    /// ### Explanation
3202    ///
3203    /// This method existed so that `#[derive(Eq)]` could check that all
3204    /// fields of a type implement `Eq`. Other users were never supposed
3205    /// to implement it and it was hidden from documentation.
3206    ///
3207    /// Unfortunately, it was not explicitly marked as unstable and some
3208    /// people have now mistakenly assumed they had to implement this method.
3209    ///
3210    /// As the method is never called by the standard library, you can safely
3211    /// remove any implementations of the method and just write `impl Eq for Foo {}`.
3212    ///
3213    /// This is a [future-incompatible] lint to transition this to a hard
3214    /// error in the future. See [issue #152336] for more details.
3215    ///
3216    /// [issue #152336]: https://github.com/rust-lang/rust/issues/152336
3217    pub INTERNAL_EQ_TRAIT_METHOD_IMPLS,
3218    Warn,
3219    "manual implementation of the internal `Eq::assert_receiver_is_total_eq` method",
3220    @future_incompatible = FutureIncompatibleInfo {
3221        reason: fcw!(FutureReleaseError #152336),
3222        report_in_deps: false,
3223    };
3224}
3225
3226pub struct InternalEqTraitMethodImpls;
#[automatically_derived]
impl ::core::marker::Copy for InternalEqTraitMethodImpls { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InternalEqTraitMethodImpls { }
#[automatically_derived]
impl ::core::clone::Clone for InternalEqTraitMethodImpls {
    #[inline]
    fn clone(&self) -> InternalEqTraitMethodImpls { *self }
}
impl ::rustc_lint_defs::LintPass for InternalEqTraitMethodImpls {
    fn name(&self) -> &'static str { "InternalEqTraitMethodImpls" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INTERNAL_EQ_TRAIT_METHOD_IMPLS]))
    }
}
impl InternalEqTraitMethodImpls {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [INTERNAL_EQ_TRAIT_METHOD_IMPLS]))
    }
}declare_lint_pass!(InternalEqTraitMethodImpls => [INTERNAL_EQ_TRAIT_METHOD_IMPLS]);
3227
3228impl<'tcx> LateLintPass<'tcx> for InternalEqTraitMethodImpls {
3229    fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx rustc_hir::ImplItem<'tcx>) {
3230        if let ImplItemImplKind::Trait { defaultness: _, trait_item_def_id: Ok(trait_item_def_id) } =
3231            item.impl_kind
3232            && cx.tcx.is_diagnostic_item(sym::assert_receiver_is_total_eq, trait_item_def_id)
3233        {
3234            cx.emit_span_lint(
3235                INTERNAL_EQ_TRAIT_METHOD_IMPLS,
3236                item.span,
3237                EqInternalMethodImplemented,
3238            );
3239        }
3240    }
3241}