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