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