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