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