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