rustc_lint/
builtin.rs

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