Skip to main content

rustc_lint/
builtin.rs

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