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