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