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