Skip to main content

rustc_lint/
internal.rs

1//! Some lints that are only useful in the compiler or crates that use compiler internals, such as
2//! Clippy.
3
4use rustc_ast as ast;
5use rustc_ast::{Pat, PatKind, Path};
6use rustc_attr_ir::find_attr;
7use rustc_hir as hir;
8use rustc_hir::def::Res;
9use rustc_hir::def_id::DefId;
10use rustc_hir::{Expr, ExprKind, HirId};
11use rustc_infer::infer::TyCtxtInferExt as _;
12use rustc_lint_defs::{declare_lint_pass, declare_tool_lint};
13use rustc_middle::ty::{self, ClausePolarity, GenericArgs};
14use rustc_span::hygiene::{ExpnKind, MacroKind};
15use rustc_span::{DUMMY_SP, Span, sym};
16use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
17use rustc_trait_selection::traits::{Obligation, ObligationCause};
18
19use crate::diagnostics::{
20    AttributeKindInFindAttr, BadOptAccessDiag, DefaultHashTypesDiag,
21    ImplicitSysrootCrateImportDiag, LintMustMatchExhaustivelyNotExhaustive, LintPassByHand,
22    MissingGenericTypeVisitableDeriveDiag, NonGlobImportTypeIrInherent, QueryInstability,
23    QueryUntracked, SymbolInternStringLiteralDiag, TyQualified, TykindDiag, TykindKind,
24    TypeIrDirectUse, TypeIrInherentUsage, TypeIrTraitUsage,
25};
26use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
27
28#[doc =
r" The `default_hash_type` lint detects use of [`std::collections::HashMap`] and"]
#[doc =
r" [`std::collections::HashSet`], suggesting the use of `FxHashMap`/`FxHashSet`."]
#[doc = r""]
#[doc =
r" This can help as `FxHasher` can perform better than the default hasher. DOS protection is"]
#[doc = r" not required as input is assumed to be trusted."]
pub static DEFAULT_HASH_TYPES: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::DEFAULT_HASH_TYPES",
            default_level: ::rustc_lint_defs::Allow,
            desc: "forbid HashMap and HashSet and suggest the FxHash* variants",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
29    /// The `default_hash_type` lint detects use of [`std::collections::HashMap`] and
30    /// [`std::collections::HashSet`], suggesting the use of `FxHashMap`/`FxHashSet`.
31    ///
32    /// This can help as `FxHasher` can perform better than the default hasher. DOS protection is
33    /// not required as input is assumed to be trusted.
34    pub rustc::DEFAULT_HASH_TYPES,
35    Allow,
36    "forbid HashMap and HashSet and suggest the FxHash* variants",
37    @report_in_external_macro = true
38}
39
40pub struct DefaultHashTypes;
#[automatically_derived]impl ::core::marker::Copy for DefaultHashTypes { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DefaultHashTypes {
}
#[automatically_derived]impl ::core::clone::Clone for DefaultHashTypes {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for DefaultHashTypes {
    fn name(&self) -> &'static str { "DefaultHashTypes" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DEFAULT_HASH_TYPES]))
    }
}
impl DefaultHashTypes {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DEFAULT_HASH_TYPES]))
    }
}declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
41
42impl LateLintPass<'_> for DefaultHashTypes {
43    fn check_path(&mut self, cx: &LateContext<'_>, path: &hir::Path<'_>, hir_id: HirId) {
44        let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
45        if #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.hir_node(hir_id) {
    hir::Node::Item(hir::Item { kind: hir::ItemKind::Use(..), .. }) |
        hir::Node::NestedUseTree(_) => true,
    _ => false,
}matches!(
46            cx.tcx.hir_node(hir_id),
47            hir::Node::Item(hir::Item { kind: hir::ItemKind::Use(..), .. })
48                | hir::Node::NestedUseTree(_)
49        ) {
50            // Don't lint imports, only actual usages.
51            return;
52        }
53        let preferred = match cx.tcx.get_diagnostic_name(def_id) {
54            Some(sym::HashMap) => "FxHashMap",
55            Some(sym::HashSet) => "FxHashSet",
56            _ => return,
57        };
58        cx.emit_span_lint(
59            DEFAULT_HASH_TYPES,
60            path.span,
61            DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) },
62        );
63    }
64}
65
66#[doc =
r" The `potential_query_instability` lint detects use of methods which can lead to"]
#[doc = r" potential query instability, such as iterating over a `HashMap`."]
#[doc = r""]
#[doc =
r" Due to the [incremental compilation](https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation.html) model,"]
#[doc =
r" queries must return deterministic, stable results. `HashMap` iteration order can change"]
#[doc =
r" between compilations, and will introduce instability if query results expose the order."]
pub static POTENTIAL_QUERY_INSTABILITY: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::POTENTIAL_QUERY_INSTABILITY",
            default_level: ::rustc_lint_defs::Allow,
            desc: "require explicit opt-in when using potentially unstable methods or functions",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
67    /// The `potential_query_instability` lint detects use of methods which can lead to
68    /// potential query instability, such as iterating over a `HashMap`.
69    ///
70    /// Due to the [incremental compilation](https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation.html) model,
71    /// queries must return deterministic, stable results. `HashMap` iteration order can change
72    /// between compilations, and will introduce instability if query results expose the order.
73    pub rustc::POTENTIAL_QUERY_INSTABILITY,
74    Allow,
75    "require explicit opt-in when using potentially unstable methods or functions",
76    @report_in_external_macro = true
77}
78
79#[doc =
r" The `untracked_query_information` lint detects use of methods which leak information not"]
#[doc =
r" tracked by the query system, such as whether a `Steal<T>` value has already been stolen. In"]
#[doc =
r" order not to break incremental compilation, such methods must be used very carefully or not"]
#[doc = r" at all."]
pub static UNTRACKED_QUERY_INFORMATION: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::UNTRACKED_QUERY_INFORMATION",
            default_level: ::rustc_lint_defs::Allow,
            desc: "require explicit opt-in when accessing information not tracked by the query system",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
80    /// The `untracked_query_information` lint detects use of methods which leak information not
81    /// tracked by the query system, such as whether a `Steal<T>` value has already been stolen. In
82    /// order not to break incremental compilation, such methods must be used very carefully or not
83    /// at all.
84    pub rustc::UNTRACKED_QUERY_INFORMATION,
85    Allow,
86    "require explicit opt-in when accessing information not tracked by the query system",
87    @report_in_external_macro = true
88}
89
90pub struct QueryStability;
#[automatically_derived]impl ::core::marker::Copy for QueryStability { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for QueryStability {
}
#[automatically_derived]impl ::core::clone::Clone for QueryStability {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for QueryStability {
    fn name(&self) -> &'static str { "QueryStability" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]))
    }
}
impl QueryStability {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]))
    }
}declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]);
91
92impl<'tcx> LateLintPass<'tcx> for QueryStability {
93    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
94        if let Some((callee_def_id, span, generic_args, _recv, _args)) =
95            get_callee_span_generic_args_and_args(cx, expr)
96            && let Ok(Some(instance)) =
97                ty::Instance::try_resolve(cx.tcx, cx.typing_env(), callee_def_id, generic_args)
98        {
99            let def_id = instance.def_id();
100            if {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &cx.tcx)
                    {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcLintQueryInstability)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(cx.tcx, def_id, RustcLintQueryInstability) {
101                cx.emit_span_lint(
102                    POTENTIAL_QUERY_INSTABILITY,
103                    span,
104                    QueryInstability { query: cx.tcx.item_name(def_id) },
105                );
106            } else if has_unstable_into_iter_predicate(cx, callee_def_id, generic_args) {
107                let call_span = span.with_hi(expr.span.hi());
108                cx.emit_span_lint(
109                    POTENTIAL_QUERY_INSTABILITY,
110                    call_span,
111                    QueryInstability { query: sym::into_iter },
112                );
113            }
114
115            if {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &cx.tcx)
                    {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcLintUntrackedQueryInformation)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(cx.tcx, def_id, RustcLintUntrackedQueryInformation) {
116                cx.emit_span_lint(
117                    UNTRACKED_QUERY_INFORMATION,
118                    span,
119                    QueryUntracked { method: cx.tcx.item_name(def_id) },
120                );
121            }
122        }
123    }
124}
125
126fn has_unstable_into_iter_predicate<'tcx>(
127    cx: &LateContext<'tcx>,
128    callee_def_id: DefId,
129    generic_args: GenericArgs<'tcx>,
130) -> bool {
131    let Some(into_iterator_def_id) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else {
132        return false;
133    };
134    let Some(into_iter_fn_def_id) = cx.tcx.lang_items().into_iter_fn() else {
135        return false;
136    };
137    let clauses = cx.tcx.clauses_of(callee_def_id).instantiate(cx.tcx, generic_args);
138    for (clause, _) in clauses {
139        let Some(trait_clause) = clause.as_trait_clause() else {
140            continue;
141        };
142        if trait_clause.def_id() != into_iterator_def_id
143            || trait_clause.polarity() != ClausePolarity::Positive
144        {
145            continue;
146        }
147        // `IntoIterator::into_iter` has no additional method args.
148        let into_iter_fn_args = cx
149            .tcx
150            .instantiate_bound_regions_with_erased(trait_clause.skip_norm_wip())
151            .trait_ref
152            .args;
153        let Ok(Some(instance)) = ty::Instance::try_resolve(
154            cx.tcx,
155            cx.typing_env(),
156            into_iter_fn_def_id,
157            into_iter_fn_args,
158        ) else {
159            continue;
160        };
161        // Does the input type's `IntoIterator` implementation have the
162        // `rustc_lint_query_instability` attribute on its `into_iter` method?
163        if {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(instance.def_id(),
                        &cx.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcLintQueryInstability)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(cx.tcx, instance.def_id(), RustcLintQueryInstability) {
164            return true;
165        }
166    }
167    false
168}
169
170/// Checks whether an expression is a function or method call and, if so, returns its `DefId`,
171/// `Span`, `GenericArgs`, and arguments. This is a slight augmentation of a similarly named Clippy
172/// function, `get_callee_generic_args_and_args`.
173fn get_callee_span_generic_args_and_args<'tcx>(
174    cx: &LateContext<'tcx>,
175    expr: &'tcx Expr<'tcx>,
176) -> Option<(DefId, Span, GenericArgs<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> {
177    if let ExprKind::Call(callee, args) = expr.kind
178        && let callee_ty = cx.typeck_results().expr_ty(callee)
179        && let ty::FnDef(callee_def_id, generic_args) = callee_ty.kind()
180    {
181        return Some((
182            *callee_def_id,
183            callee.span,
184            generic_args.no_bound_vars().unwrap(),
185            None,
186            args,
187        ));
188    }
189    if let ExprKind::MethodCall(segment, recv, args, _) = expr.kind
190        && let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
191    {
192        let generic_args = cx.typeck_results().node_args(expr.hir_id);
193        return Some((method_def_id, segment.ident.span, generic_args, Some(recv), args));
194    }
195    None
196}
197
198#[doc =
r" The `usage_of_ty_tykind` lint detects usages of `ty::TyKind::<kind>`,"]
#[doc = r" where `ty::<kind>` would suffice."]
pub static USAGE_OF_TY_TYKIND: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::USAGE_OF_TY_TYKIND",
            default_level: ::rustc_lint_defs::Allow,
            desc: "usage of `ty::TyKind` outside of the `ty::sty` module",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
199    /// The `usage_of_ty_tykind` lint detects usages of `ty::TyKind::<kind>`,
200    /// where `ty::<kind>` would suffice.
201    pub rustc::USAGE_OF_TY_TYKIND,
202    Allow,
203    "usage of `ty::TyKind` outside of the `ty::sty` module",
204    @report_in_external_macro = true
205}
206
207#[doc = r" The `usage_of_qualified_ty` lint detects usages of `ty::TyKind`,"]
#[doc = r" where `Ty` should be used instead."]
pub static USAGE_OF_QUALIFIED_TY: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::USAGE_OF_QUALIFIED_TY",
            default_level: ::rustc_lint_defs::Allow,
            desc: "using `ty::{Ty,TyCtxt}` instead of importing it",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
208    /// The `usage_of_qualified_ty` lint detects usages of `ty::TyKind`,
209    /// where `Ty` should be used instead.
210    pub rustc::USAGE_OF_QUALIFIED_TY,
211    Allow,
212    "using `ty::{Ty,TyCtxt}` instead of importing it",
213    @report_in_external_macro = true
214}
215
216pub struct TyTyKind;
#[automatically_derived]impl ::core::marker::Copy for TyTyKind { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TyTyKind {
}
#[automatically_derived]impl ::core::clone::Clone for TyTyKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for TyTyKind {
    fn name(&self) -> &'static str { "TyTyKind" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [USAGE_OF_TY_TYKIND, USAGE_OF_QUALIFIED_TY]))
    }
}
impl TyTyKind {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [USAGE_OF_TY_TYKIND, USAGE_OF_QUALIFIED_TY]))
    }
}declare_lint_pass!(TyTyKind => [
217    USAGE_OF_TY_TYKIND,
218    USAGE_OF_QUALIFIED_TY,
219]);
220
221impl<'tcx> LateLintPass<'tcx> for TyTyKind {
222    fn check_path(
223        &mut self,
224        cx: &LateContext<'tcx>,
225        path: &rustc_hir::Path<'tcx>,
226        _: rustc_hir::HirId,
227    ) {
228        if let Some(segment) = path.segments.iter().nth_back(1)
229            && lint_ty_kind_usage(cx, &segment.res)
230        {
231            let span =
232                path.span.with_hi(segment.args.map_or(segment.ident.span, |a| a.span_ext).hi());
233            cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind { suggestion: span });
234        }
235    }
236
237    fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx, hir::AmbigArg>) {
238        match &ty.kind {
239            hir::TyKind::Path(hir::QPath::Resolved(_, path)) => {
240                if lint_ty_kind_usage(cx, &path.res) {
241                    let span = match cx.tcx.parent_hir_node(ty.hir_id) {
242                        hir::Node::PatExpr(hir::PatExpr {
243                            kind: hir::PatExprKind::Path(qpath),
244                            ..
245                        })
246                        | hir::Node::Pat(hir::Pat {
247                            kind:
248                                hir::PatKind::TupleStruct(qpath, ..) | hir::PatKind::Struct(qpath, ..),
249                            ..
250                        })
251                        | hir::Node::Expr(
252                            hir::Expr {
253                                kind:
254                                    hir::ExprKind::Path(qpath)
255                                    | hir::ExprKind::RawHandle(hir::PlaceExpr { path: qpath, .. }),
256                                ..
257                            }
258                            | &hir::Expr { kind: hir::ExprKind::Struct(qpath, ..), .. },
259                        ) => {
260                            if let hir::QPath::TypeRelative(qpath_ty, ..) = qpath
261                                && qpath_ty.hir_id == ty.hir_id
262                            {
263                                Some(path.span)
264                            } else {
265                                None
266                            }
267                        }
268                        _ => None,
269                    };
270
271                    match span {
272                        Some(span) => {
273                            cx.emit_span_lint(
274                                USAGE_OF_TY_TYKIND,
275                                path.span,
276                                TykindKind { suggestion: span },
277                            );
278                        }
279                        None => cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
280                    }
281                } else if !ty.span.from_expansion()
282                    && path.segments.len() > 1
283                    && let Some(ty) = is_ty_or_ty_ctxt(cx, path)
284                {
285                    cx.emit_span_lint(
286                        USAGE_OF_QUALIFIED_TY,
287                        path.span,
288                        TyQualified { ty, suggestion: path.span },
289                    );
290                }
291            }
292            _ => {}
293        }
294    }
295}
296
297fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
298    if let Some(did) = res.opt_def_id() {
299        cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
300    } else {
301        false
302    }
303}
304
305fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &hir::Path<'_>) -> Option<String> {
306    match path.res {
307        Res::Def(_, def_id) => {
308            if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(def_id) {
309                return Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", name,
                gen_args(path.segments.last().unwrap())))
    })format!("{}{}", name, gen_args(path.segments.last().unwrap())));
310            }
311        }
312        // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
313        Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
314            if let ty::Adt(adt, args) =
315                cx.tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
316                && let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
317            {
318                return Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}<{1}>", name, args[0]))
    })format!("{}<{}>", name, args[0]));
319            }
320        }
321        _ => (),
322    }
323
324    None
325}
326
327fn gen_args(segment: &hir::PathSegment<'_>) -> String {
328    if let Some(args) = &segment.args {
329        let lifetimes = args
330            .args
331            .iter()
332            .filter_map(|arg| {
333                if let hir::GenericArg::Lifetime(lt) = arg {
334                    Some(lt.ident.to_string())
335                } else {
336                    None
337                }
338            })
339            .collect::<Vec<_>>();
340
341        if !lifetimes.is_empty() {
342            return ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", lifetimes.join(", ")))
    })format!("<{}>", lifetimes.join(", "));
343        }
344    }
345
346    String::new()
347}
348
349#[doc = r" The `non_glob_import_of_type_ir_inherent_item` lint detects"]
#[doc = r" non-glob imports of module `rustc_type_ir::inherent`."]
pub static NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT",
            default_level: ::rustc_lint_defs::Allow,
            desc: "non-glob import of `rustc_type_ir::inherent`",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
350    /// The `non_glob_import_of_type_ir_inherent_item` lint detects
351    /// non-glob imports of module `rustc_type_ir::inherent`.
352    pub rustc::NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
353    Allow,
354    "non-glob import of `rustc_type_ir::inherent`",
355    @report_in_external_macro = true
356}
357
358#[doc =
r" The `usage_of_type_ir_inherent` lint detects usage of `rustc_type_ir::inherent`."]
#[doc = r""]
#[doc = r" This module should only be used within the trait solver."]
pub static USAGE_OF_TYPE_IR_INHERENT: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::USAGE_OF_TYPE_IR_INHERENT",
            default_level: ::rustc_lint_defs::Allow,
            desc: "usage `rustc_type_ir::inherent` outside of trait system",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
359    /// The `usage_of_type_ir_inherent` lint detects usage of `rustc_type_ir::inherent`.
360    ///
361    /// This module should only be used within the trait solver.
362    pub rustc::USAGE_OF_TYPE_IR_INHERENT,
363    Allow,
364    "usage `rustc_type_ir::inherent` outside of trait system",
365    @report_in_external_macro = true
366}
367
368#[doc =
r" The `usage_of_type_ir_traits` lint detects usage of `rustc_type_ir::Interner`,"]
#[doc = r" or `rustc_infer::InferCtxtLike`."]
#[doc = r""]
#[doc =
r" Methods of this trait should only be used within the type system abstraction layer,"]
#[doc =
r" and in the generic next trait solver implementation. Look for an analogously named"]
#[doc = r" method on `TyCtxt` or `InferCtxt` (respectively)."]
pub static USAGE_OF_TYPE_IR_TRAITS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::USAGE_OF_TYPE_IR_TRAITS",
            default_level: ::rustc_lint_defs::Allow,
            desc: "usage `rustc_type_ir`-specific abstraction traits outside of trait system",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
369    /// The `usage_of_type_ir_traits` lint detects usage of `rustc_type_ir::Interner`,
370    /// or `rustc_infer::InferCtxtLike`.
371    ///
372    /// Methods of this trait should only be used within the type system abstraction layer,
373    /// and in the generic next trait solver implementation. Look for an analogously named
374    /// method on `TyCtxt` or `InferCtxt` (respectively).
375    pub rustc::USAGE_OF_TYPE_IR_TRAITS,
376    Allow,
377    "usage `rustc_type_ir`-specific abstraction traits outside of trait system",
378    @report_in_external_macro = true
379}
380#[doc =
r" The `direct_use_of_rustc_type_ir` lint detects usage of `rustc_type_ir`."]
#[doc = r""]
#[doc =
r" This module should only be used within the trait solver and some desirable"]
#[doc = r" crates like rustc_middle."]
pub static DIRECT_USE_OF_RUSTC_TYPE_IR: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::DIRECT_USE_OF_RUSTC_TYPE_IR",
            default_level: ::rustc_lint_defs::Allow,
            desc: "usage `rustc_type_ir` abstraction outside of trait system",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
381    /// The `direct_use_of_rustc_type_ir` lint detects usage of `rustc_type_ir`.
382    ///
383    /// This module should only be used within the trait solver and some desirable
384    /// crates like rustc_middle.
385    pub rustc::DIRECT_USE_OF_RUSTC_TYPE_IR,
386    Allow,
387    "usage `rustc_type_ir` abstraction outside of trait system",
388    @report_in_external_macro = true
389}
390
391pub struct TypeIr;
#[automatically_derived]impl ::core::marker::Copy for TypeIr { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TypeIr {
}
#[automatically_derived]impl ::core::clone::Clone for TypeIr {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for TypeIr {
    fn name(&self) -> &'static str { "TypeIr" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DIRECT_USE_OF_RUSTC_TYPE_IR,
                        NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
                        USAGE_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_TRAITS]))
    }
}
impl TypeIr {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [DIRECT_USE_OF_RUSTC_TYPE_IR,
                        NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
                        USAGE_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_TRAITS]))
    }
}declare_lint_pass!(TypeIr => [
392    DIRECT_USE_OF_RUSTC_TYPE_IR,
393    NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
394    USAGE_OF_TYPE_IR_INHERENT,
395    USAGE_OF_TYPE_IR_TRAITS
396]);
397
398impl<'tcx> LateLintPass<'tcx> for TypeIr {
399    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
400        let res_def_id = match expr.kind {
401            hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => path.res.opt_def_id(),
402            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) | hir::ExprKind::MethodCall(..) => {
403                cx.typeck_results().type_dependent_def_id(expr.hir_id)
404            }
405            _ => return,
406        };
407        let Some(res_def_id) = res_def_id else {
408            return;
409        };
410        if let Some(assoc_item) = cx.tcx.opt_associated_item(res_def_id)
411            && let Some(trait_def_id) = assoc_item.trait_container(cx.tcx)
412            && (cx.tcx.is_diagnostic_item(sym::type_ir_interner, trait_def_id)
413                | cx.tcx.is_diagnostic_item(sym::type_ir_infer_ctxt_like, trait_def_id))
414        {
415            cx.emit_span_lint(USAGE_OF_TYPE_IR_TRAITS, expr.span, TypeIrTraitUsage);
416        }
417    }
418
419    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
420        let rustc_hir::ItemKind::Use(tree) = item.kind else {
421            return;
422        };
423
424        check_use(cx, tree, ::alloc::vec::Vec::new()vec![]);
425
426        fn check_use<'tcx>(
427            cx: &LateContext<'_>,
428            tree: hir::UseTree<'tcx>,
429            mut prefix: Vec<&'tcx hir::PathSegment<'tcx>>,
430        ) {
431            let is_mod_inherent = |res: Res| {
432                res.opt_def_id()
433                    .is_some_and(|def_id| cx.tcx.is_diagnostic_item(sym::type_ir_inherent, def_id))
434            };
435
436            prefix.extend(tree.prefix.segments);
437
438            match tree.kind {
439                rustc_hir::UseKind::Single(_) | rustc_hir::UseKind::Glob => {}
440                rustc_hir::UseKind::Nested { items } => {
441                    for (nested, _, _) in items {
442                        check_use(cx, *nested, prefix.clone())
443                    }
444                }
445            }
446
447            // Path segments except for the final.
448            if let Some(seg) = prefix.iter().find(|seg| is_mod_inherent(seg.res)) {
449                cx.emit_span_lint(USAGE_OF_TYPE_IR_INHERENT, seg.ident.span, TypeIrInherentUsage);
450            }
451            // Final path resolutions, like `use rustc_type_ir::inherent`
452            else if let Some(type_ns) = tree.prefix.res.type_ns
453                && is_mod_inherent(type_ns)
454            {
455                cx.emit_span_lint(
456                    USAGE_OF_TYPE_IR_INHERENT,
457                    prefix.last().unwrap().ident.span,
458                    TypeIrInherentUsage,
459                );
460            }
461
462            let (lo, hi, snippet) = match prefix {
463                [.., penultimate, segment]
464                    if is_mod_inherent(penultimate.res)
465                        && let rustc_hir::UseKind::Single(ident) = tree.kind =>
466                {
467                    (segment.ident.span, ident.span, "*")
468                }
469                [.., segment]
470                    if let Some(type_ns) = tree.prefix.res.type_ns
471                        && is_mod_inherent(type_ns)
472                        && let rustc_hir::UseKind::Single(ident) = tree.kind =>
473                {
474                    let (lo, snippet) =
475                        match cx.tcx.sess.source_map().span_to_snippet(tree.prefix.span).as_deref()
476                        {
477                            Ok("self") => (tree.prefix.span, "*"),
478                            _ => (segment.ident.span.shrink_to_hi(), "::*"),
479                        };
480                    (lo, if segment.ident == ident { lo } else { ident.span }, snippet)
481                }
482                _ => return,
483            };
484            cx.emit_span_lint(
485                NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
486                tree.prefix.span,
487                NonGlobImportTypeIrInherent {
488                    suggestion: (lo.ctxt() == hi.ctxt()).then(|| lo.to(hi)),
489                    snippet,
490                },
491            );
492        }
493    }
494
495    fn check_path(
496        &mut self,
497        cx: &LateContext<'tcx>,
498        path: &rustc_hir::Path<'tcx>,
499        _: rustc_hir::HirId,
500    ) {
501        if let Some(seg) = path.segments.iter().find(|seg| {
502            seg.res
503                .opt_def_id()
504                .is_some_and(|def_id| cx.tcx.is_diagnostic_item(sym::type_ir, def_id))
505        }) {
506            cx.emit_span_lint(DIRECT_USE_OF_RUSTC_TYPE_IR, seg.ident.span, TypeIrDirectUse);
507        }
508    }
509}
510
511#[doc =
r" The `lint_pass_impl_without_macro` detects manual implementations of a lint"]
#[doc = r" pass, without using [`declare_lint_pass`] or [`impl_lint_pass`]."]
pub static LINT_PASS_IMPL_WITHOUT_MACRO: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::LINT_PASS_IMPL_WITHOUT_MACRO",
            default_level: ::rustc_lint_defs::Allow,
            desc: "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros",
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
512    /// The `lint_pass_impl_without_macro` detects manual implementations of a lint
513    /// pass, without using [`declare_lint_pass`] or [`impl_lint_pass`].
514    pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
515    Allow,
516    "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
517}
518
519pub struct LintPassImpl;
#[automatically_derived]impl ::core::marker::Copy for LintPassImpl { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for LintPassImpl {
}
#[automatically_derived]impl ::core::clone::Clone for LintPassImpl {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for LintPassImpl {
    fn name(&self) -> &'static str { "LintPassImpl" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [LINT_PASS_IMPL_WITHOUT_MACRO]))
    }
}
impl LintPassImpl {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [LINT_PASS_IMPL_WITHOUT_MACRO]))
    }
}declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
520
521impl EarlyLintPass for LintPassImpl {
522    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
523        if let ast::ItemKind::Impl(ast::Impl { of_trait: Some(of_trait), .. }) = &item.kind
524            && let Some(last) = of_trait.trait_ref.path.segments.last()
525            && last.ident.name == sym::LintPass
526        {
527            let expn_data = of_trait.trait_ref.path.span.ctxt().outer_expn_data();
528            let call_site = expn_data.call_site;
529            if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
530                && call_site.ctxt().outer_expn_data().kind
531                    != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
532            {
533                cx.emit_span_lint(
534                    LINT_PASS_IMPL_WITHOUT_MACRO,
535                    of_trait.trait_ref.path.span,
536                    LintPassByHand,
537                );
538            }
539        }
540    }
541}
542
543#[doc =
r" The `bad_opt_access` lint detects accessing options by field instead of"]
#[doc = r" the wrapper function."]
pub static BAD_OPT_ACCESS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::BAD_OPT_ACCESS",
            default_level: ::rustc_lint_defs::Deny,
            desc: "prevent using options by field access when there is a wrapper function",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
544    /// The `bad_opt_access` lint detects accessing options by field instead of
545    /// the wrapper function.
546    pub rustc::BAD_OPT_ACCESS,
547    Deny,
548    "prevent using options by field access when there is a wrapper function",
549    @report_in_external_macro = true
550}
551
552pub struct BadOptAccess;
#[automatically_derived]impl ::core::marker::Copy for BadOptAccess { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for BadOptAccess {
}
#[automatically_derived]impl ::core::clone::Clone for BadOptAccess {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for BadOptAccess {
    fn name(&self) -> &'static str { "BadOptAccess" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [BAD_OPT_ACCESS]))
    }
}
impl BadOptAccess {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [BAD_OPT_ACCESS]))
    }
}declare_lint_pass!(BadOptAccess => [BAD_OPT_ACCESS]);
553
554impl LateLintPass<'_> for BadOptAccess {
555    fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
556        let hir::ExprKind::Field(base, target) = expr.kind else { return };
557        let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
558        // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
559        // avoided.
560        if !{
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(adt_def.did(), &cx.tcx)
                    {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcLintOptTy) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(cx.tcx, adt_def.did(), RustcLintOptTy) {
561            return;
562        }
563
564        for field in adt_def.all_fields() {
565            if field.name == target.name
566                && let Some(lint_message) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(field.did, &cx.tcx)
                {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcLintOptDenyFieldAccess {
                        lint_message }) => {
                        break 'done Some(lint_message);
                    }
                    ::rustc_attr_ir::Attribute::Tool { .. } |
                        ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(cx.tcx, field.did, RustcLintOptDenyFieldAccess { lint_message, } => lint_message)
567            {
568                cx.emit_span_lint(
569                    BAD_OPT_ACCESS,
570                    expr.span,
571                    BadOptAccessDiag { msg: lint_message.as_str() },
572                );
573            }
574        }
575    }
576}
577
578#[doc =
r" The `symbol_intern_string_literal` lint detects `Symbol::intern` or `Ident::from_str_and_span` being called on a string literal"]
pub static SYMBOL_INTERN_STRING_LITERAL: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::SYMBOL_INTERN_STRING_LITERAL",
            default_level: ::rustc_lint_defs::Allow,
            desc: "Forbid uses of string literals in `Symbol::intern` or `Ident::from_str_and_span`, suggesting preinterning instead",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
579    /// The `symbol_intern_string_literal` lint detects `Symbol::intern` or `Ident::from_str_and_span` being called on a string literal
580    pub rustc::SYMBOL_INTERN_STRING_LITERAL,
581    Allow,
582    "Forbid uses of string literals in `Symbol::intern` or `Ident::from_str_and_span`, suggesting preinterning instead",
583    @report_in_external_macro = true
584}
585
586pub struct SymbolInternStringLiteral;
#[automatically_derived]impl ::core::marker::Copy for
    SymbolInternStringLiteral {
}
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SymbolInternStringLiteral {
}
#[automatically_derived]impl ::core::clone::Clone for
    SymbolInternStringLiteral {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for SymbolInternStringLiteral {
    fn name(&self) -> &'static str { "SymbolInternStringLiteral" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [SYMBOL_INTERN_STRING_LITERAL]))
    }
}
impl SymbolInternStringLiteral {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [SYMBOL_INTERN_STRING_LITERAL]))
    }
}declare_lint_pass!(SymbolInternStringLiteral => [SYMBOL_INTERN_STRING_LITERAL]);
587
588impl<'tcx> LateLintPass<'tcx> for SymbolInternStringLiteral {
589    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) {
590        if let hir::ExprKind::Call(path, args) = expr.kind
591            && let hir::ExprKind::Path(ref qpath) = path.kind
592            && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
593        {
594            let (arg, fn_name) = if cx.tcx.is_diagnostic_item(sym::SymbolIntern, def_id)
595                && let [arg] = args
596            {
597                (arg, "Symbol::intern")
598            } else if cx.tcx.is_diagnostic_item(sym::ident_from_str_and_span, def_id)
599                && let [arg, _] = args
600            {
601                (arg, "Ident::from_str_and_span")
602            } else {
603                return;
604            };
605            if let hir::ExprKind::Lit(kind) = arg.kind
606                && let rustc_ast::LitKind::Str(_, _) = kind.node
607            {
608                cx.emit_span_lint(
609                    SYMBOL_INTERN_STRING_LITERAL,
610                    kind.span,
611                    SymbolInternStringLiteralDiag { fn_name },
612                );
613            }
614        }
615    }
616}
617
618#[doc =
r" The `implicit_sysroot_crate_import` detects use of `extern crate` to import non-sysroot crates"]
#[doc =
r" (e.g. crates.io deps) from the sysroot, which is dangerous because these crates are not guaranteed"]
#[doc =
r" to exist exactly once, and so may be missing entirely or appear multiple times resulting in ambiguity."]
pub static IMPLICIT_SYSROOT_CRATE_IMPORT: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::IMPLICIT_SYSROOT_CRATE_IMPORT",
            default_level: ::rustc_lint_defs::Allow,
            desc: "Forbid uses of non-sysroot crates in `extern crate`",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
619    /// The `implicit_sysroot_crate_import` detects use of `extern crate` to import non-sysroot crates
620    /// (e.g. crates.io deps) from the sysroot, which is dangerous because these crates are not guaranteed
621    /// to exist exactly once, and so may be missing entirely or appear multiple times resulting in ambiguity.
622    pub rustc::IMPLICIT_SYSROOT_CRATE_IMPORT,
623    Allow,
624    "Forbid uses of non-sysroot crates in `extern crate`",
625    @report_in_external_macro = true
626}
627
628pub struct ImplicitSysrootCrateImport;
#[automatically_derived]impl ::core::marker::Copy for
    ImplicitSysrootCrateImport {
}
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ImplicitSysrootCrateImport {
}
#[automatically_derived]impl ::core::clone::Clone for
    ImplicitSysrootCrateImport {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for ImplicitSysrootCrateImport {
    fn name(&self) -> &'static str { "ImplicitSysrootCrateImport" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [IMPLICIT_SYSROOT_CRATE_IMPORT]))
    }
}
impl ImplicitSysrootCrateImport {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [IMPLICIT_SYSROOT_CRATE_IMPORT]))
    }
}declare_lint_pass!(ImplicitSysrootCrateImport => [IMPLICIT_SYSROOT_CRATE_IMPORT]);
629
630impl EarlyLintPass for ImplicitSysrootCrateImport {
631    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
632        fn is_whitelisted(crate_name: &str) -> bool {
633            // Whitelist of allowed crates.
634            crate_name.starts_with("rustc_")
635                || #[allow(non_exhaustive_omitted_patterns)] match crate_name {
    "test" | "self" | "core" | "alloc" | "std" | "proc_macro" |
        "tikv_jemalloc_sys" => true,
    _ => false,
}matches!(
636                    crate_name,
637                    "test" | "self" | "core" | "alloc" | "std" | "proc_macro" | "tikv_jemalloc_sys"
638                )
639        }
640
641        if let ast::ItemKind::ExternCrate(original_name, imported_name) = &item.kind {
642            let name = original_name.as_ref().unwrap_or(&imported_name.name).as_str();
643            let externs = &cx.builder.sess().opts.externs;
644            if externs.get(name).is_none() && !is_whitelisted(name) {
645                cx.emit_span_lint(
646                    IMPLICIT_SYSROOT_CRATE_IMPORT,
647                    item.span,
648                    ImplicitSysrootCrateImportDiag { name },
649                );
650            }
651        }
652    }
653}
654
655pub static BAD_USE_OF_FIND_ATTR: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::BAD_USE_OF_FIND_ATTR",
            default_level: ::rustc_lint_defs::Allow,
            desc: "Forbid `AttributeKind::` as a prefix in `find_attr!` macros.",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
656    pub rustc::BAD_USE_OF_FIND_ATTR,
657    Allow,
658    "Forbid `AttributeKind::` as a prefix in `find_attr!` macros.",
659    @report_in_external_macro = true
660}
661pub struct BadUseOfFindAttr;
#[automatically_derived]impl ::core::marker::Copy for BadUseOfFindAttr { }
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for BadUseOfFindAttr {
}
#[automatically_derived]impl ::core::clone::Clone for BadUseOfFindAttr {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for BadUseOfFindAttr {
    fn name(&self) -> &'static str { "BadUseOfFindAttr" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [BAD_USE_OF_FIND_ATTR]))
    }
}
impl BadUseOfFindAttr {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [BAD_USE_OF_FIND_ATTR]))
    }
}declare_lint_pass!(BadUseOfFindAttr => [BAD_USE_OF_FIND_ATTR]);
662
663impl EarlyLintPass for BadUseOfFindAttr {
664    fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &rustc_ast::Arm) {
665        fn path_contains_attribute_kind(cx: &EarlyContext<'_>, path: &Path) {
666            for segment in &path.segments {
667                if segment.ident.as_str() == "AttributeKind" {
668                    cx.emit_span_lint(
669                        BAD_USE_OF_FIND_ATTR,
670                        segment.span(),
671                        AttributeKindInFindAttr,
672                    );
673                }
674            }
675        }
676
677        fn find_attr_kind_in_pat(cx: &EarlyContext<'_>, pat: &Pat) {
678            match &pat.kind {
679                PatKind::Struct(_, path, fields, _) => {
680                    path_contains_attribute_kind(cx, path);
681                    for field in fields {
682                        find_attr_kind_in_pat(cx, &field.pat);
683                    }
684                }
685                PatKind::TupleStruct(_, path, fields) => {
686                    path_contains_attribute_kind(cx, path);
687                    for field in fields {
688                        find_attr_kind_in_pat(cx, &field);
689                    }
690                }
691                PatKind::Or(options) => {
692                    for pat in options {
693                        find_attr_kind_in_pat(cx, pat);
694                    }
695                }
696                PatKind::Path(_, path) => {
697                    path_contains_attribute_kind(cx, path);
698                }
699                PatKind::Tuple(elems) => {
700                    for pat in elems {
701                        find_attr_kind_in_pat(cx, pat);
702                    }
703                }
704                PatKind::Deref(pat) => {
705                    find_attr_kind_in_pat(cx, pat);
706                }
707                PatKind::Ref(..) => {
708                    find_attr_kind_in_pat(cx, pat);
709                }
710                PatKind::Slice(elems) => {
711                    for pat in elems {
712                        find_attr_kind_in_pat(cx, pat);
713                    }
714                }
715
716                PatKind::Guard(pat, ..) => {
717                    find_attr_kind_in_pat(cx, pat);
718                }
719                PatKind::Paren(pat) => {
720                    find_attr_kind_in_pat(cx, pat);
721                }
722                PatKind::Expr(..)
723                | PatKind::Range(..)
724                | PatKind::MacCall(..)
725                | PatKind::Rest
726                | PatKind::Missing
727                | PatKind::Err(..)
728                | PatKind::Ident(..)
729                | PatKind::Never
730                | PatKind::Wild => {}
731            }
732        }
733
734        if let Some(expn_data) = arm.span.source_callee()
735            && let ExpnKind::Macro(_, name) = expn_data.kind
736            && name.as_str() == "find_attr"
737        {
738            find_attr_kind_in_pat(cx, &arm.pat);
739        }
740    }
741}
742
743pub static MUST_MATCH_EXHAUSTIVELY: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::MUST_MATCH_EXHAUSTIVELY",
            default_level: ::rustc_lint_defs::Allow,
            desc: "Forbids matches with wildcards, or if-let matching on enums marked with `#[lint::must_match_exhaustively]`",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
744    pub rustc::MUST_MATCH_EXHAUSTIVELY,
745    Allow,
746    "Forbids matches with wildcards, or if-let matching on enums marked with `#[lint::must_match_exhaustively]`",
747    @report_in_external_macro = true
748}
749pub struct LintMustMatchExhaustively;
#[automatically_derived]impl ::core::marker::Copy for
    LintMustMatchExhaustively {
}
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for LintMustMatchExhaustively {
}
#[automatically_derived]impl ::core::clone::Clone for
    LintMustMatchExhaustively {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for LintMustMatchExhaustively {
    fn name(&self) -> &'static str { "LintMustMatchExhaustively" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MUST_MATCH_EXHAUSTIVELY]))
    }
}
impl LintMustMatchExhaustively {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MUST_MATCH_EXHAUSTIVELY]))
    }
}declare_lint_pass!(LintMustMatchExhaustively => [MUST_MATCH_EXHAUSTIVELY]);
750
751fn is_must_match_exhaustively(cx: &LateContext<'_>, id: HirId) -> Option<Span> {
752    let res = cx.typeck_results();
753
754    let ty = res.node_type(id);
755
756    let ty = if let ty::Ref(_, ty, _) = ty.kind() { *ty } else { ty };
757
758    if let Some(adt_def) = ty.ty_adt_def()
759        && adt_def.is_enum()
760    {
761        {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(adt_def.did(), &cx.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(LintMustMatchExhaustively(span))
                        => {
                        break 'done Some(*span);
                    }
                    ::rustc_attr_ir::Attribute::Tool { .. } |
                        ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(cx.tcx, adt_def.did(), LintMustMatchExhaustively(span) => *span)
762    } else {
763        None
764    }
765}
766
767fn pat_is_not_exhaustive_heuristic(pat: &hir::Pat<'_>) -> Option<(Span, &'static str)> {
768    match pat.kind {
769        hir::PatKind::Missing => None,
770        hir::PatKind::Wild => Some((pat.span, "because of this wildcard pattern")),
771        hir::PatKind::Binding(_, _, _, Some(pat)) => pat_is_not_exhaustive_heuristic(pat),
772        hir::PatKind::Binding(..) => Some((pat.span, "because of this variable binding")),
773        hir::PatKind::Struct(..) => None,
774        hir::PatKind::TupleStruct(..) => None,
775        hir::PatKind::Or(..) => None,
776        hir::PatKind::Never => None,
777        hir::PatKind::Tuple(..) => None,
778        hir::PatKind::Deref(pat) => pat_is_not_exhaustive_heuristic(&*pat),
779        hir::PatKind::Ref(pat, _, _) => pat_is_not_exhaustive_heuristic(&*pat),
780        hir::PatKind::Expr(..) => None,
781        hir::PatKind::Guard(..) => None,
782        hir::PatKind::Range(..) => None,
783        hir::PatKind::Slice(..) => None,
784        hir::PatKind::Err(..) => None,
785    }
786}
787
788impl<'tcx> LateLintPass<'tcx> for LintMustMatchExhaustively {
789    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
790        match expr.kind {
791            // This is not perfect exhaustiveness checking, that's why this is just a rustc internal
792            // attribute. But it catches most reasonable cases
793            hir::ExprKind::Match(expr, arms, _) => {
794                if let Some(attr_span) = is_must_match_exhaustively(cx, expr.hir_id) {
795                    for arm in arms {
796                        if let Some((span, message)) = pat_is_not_exhaustive_heuristic(arm.pat) {
797                            cx.emit_span_lint(
798                                MUST_MATCH_EXHAUSTIVELY,
799                                expr.span,
800                                LintMustMatchExhaustivelyNotExhaustive {
801                                    attr_span,
802                                    pat_span: span,
803                                    message,
804                                },
805                            );
806                        }
807                    }
808                }
809            }
810            hir::ExprKind::Let(expr, ..) => {
811                if let Some(attr_span) = is_must_match_exhaustively(cx, expr.init.hir_id) {
812                    cx.emit_span_lint(
813                        MUST_MATCH_EXHAUSTIVELY,
814                        expr.span,
815                        LintMustMatchExhaustivelyNotExhaustive {
816                            attr_span,
817                            pat_span: expr.span,
818                            message: "using `if let` only matches on one variant (try using `match`)",
819                        },
820                    );
821                }
822            }
823            _ => {}
824        }
825    }
826
827    fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx rustc_hir::Stmt<'tcx>) {
828        match stmt.kind {
829            rustc_hir::StmtKind::Let(let_stmt) => {
830                if let_stmt.els.is_some()
831                    && let Some(attr_span) = is_must_match_exhaustively(cx, let_stmt.pat.hir_id)
832                {
833                    cx.emit_span_lint(
834                        MUST_MATCH_EXHAUSTIVELY,
835                        let_stmt.span,
836                        LintMustMatchExhaustivelyNotExhaustive {
837                            attr_span,
838                            pat_span: let_stmt.pat.span,
839                            message: "using `let else` only matches on one variant (try using `match`)",
840                        },
841                    );
842                }
843            }
844            _ => {}
845        }
846    }
847}
848
849#[doc =
r" The `missing_generic_type_visitable_derive` lint detects types implementing `TypeVisitable`"]
#[doc = r" but not deriving `GenericTypeVisitable`."]
#[doc = r""]
#[doc =
r" `GenericTypeVisitable` is the analog of `TypeVisitable` used by rust-analyzer, and needs to"]
#[doc =
r" be implemented whenever `TypeVisitable` is. See [`rustc_type_ir::generic_visit`] for more"]
#[doc = r" information."]
pub static MISSING_GENERIC_TYPE_VISITABLE_DERIVE: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: &"rustc::MISSING_GENERIC_TYPE_VISITABLE_DERIVE",
            default_level: ::rustc_lint_defs::Allow,
            desc: "Forbid implementing `TypeVisitable` without deriving `GenericTypeVisitable`",
            report_in_external_macro: true,
            is_externally_loaded: true,
            ..
        };declare_tool_lint! {
850    /// The `missing_generic_type_visitable_derive` lint detects types implementing `TypeVisitable`
851    /// but not deriving `GenericTypeVisitable`.
852    ///
853    /// `GenericTypeVisitable` is the analog of `TypeVisitable` used by rust-analyzer, and needs to
854    /// be implemented whenever `TypeVisitable` is. See [`rustc_type_ir::generic_visit`] for more
855    /// information.
856    pub rustc::MISSING_GENERIC_TYPE_VISITABLE_DERIVE,
857    // This lint is meant to be manually enabled in selected crates (currently only `rustc_type_ir`)
858    Allow,
859    "Forbid implementing `TypeVisitable` without deriving `GenericTypeVisitable`",
860    @report_in_external_macro = true
861}
862
863pub struct MissingGenericTypeVisitableDerive;
#[automatically_derived]impl ::core::marker::Copy for
    MissingGenericTypeVisitableDerive {
}
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for MissingGenericTypeVisitableDerive {
}
#[automatically_derived]impl ::core::clone::Clone for
    MissingGenericTypeVisitableDerive {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for MissingGenericTypeVisitableDerive {
    fn name(&self) -> &'static str { "MissingGenericTypeVisitableDerive" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_GENERIC_TYPE_VISITABLE_DERIVE]))
    }
}
impl MissingGenericTypeVisitableDerive {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [MISSING_GENERIC_TYPE_VISITABLE_DERIVE]))
    }
}declare_lint_pass!(MissingGenericTypeVisitableDerive => [MISSING_GENERIC_TYPE_VISITABLE_DERIVE]);
864
865impl<'tcx> LateLintPass<'tcx> for MissingGenericTypeVisitableDerive {
866    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
867        // lint ADTs except unions, as neither trait can be implemented on the latter
868        if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) => true,
    _ => false,
}matches!(item.kind, hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..))
869            && let Some(regular_id) = cx.tcx.get_diagnostic_item(sym::TypeVisitable)
870            && let Some(generic_id) = cx.tcx.get_diagnostic_item(sym::GenericTypeVisitable)
871            && let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env())
872            && let self_ty = {
873                let self_id = item.owner_id.to_def_id();
874                let args = infcx.fresh_args_for_item(DUMMY_SP, self_id);
875                cx.tcx.type_of(self_id).instantiate(cx.tcx, args).skip_norm_wip()
876            }
877            // check whether `Self: TypeVisitable<I>` holds for some `I`..
878            && {
879                let predicate =
880                    ty::TraitRef::new(cx.tcx, regular_id, [self_ty, infcx.next_ty_var(DUMMY_SP)]);
881                let obligation =
882                    Obligation::new(cx.tcx, ObligationCause::dummy(), param_env, predicate);
883
884                // NOTE: I initially went with `predicate_must_hold_modulo_regions` (which is what's
885                // used by Clippy's [`implements_trait`](https://doc.rust-lang.org/nightly/nightly-rustc/clippy_utils/ty/fn.implements_trait.html),
886                // but that returned `false` more often than I'd hoped, and so I went with the
887                // next-most strict function.
888                infcx.predicate_may_hold(&obligation)
889            }
890            // ..while `Self: GenericTypeVisitable<V>` doesn't
891            && {
892                let predicate =
893                    ty::TraitRef::new(cx.tcx, generic_id, [self_ty, infcx.next_ty_var(DUMMY_SP)]);
894                let obligation =
895                    Obligation::new(cx.tcx, ObligationCause::dummy(), param_env, predicate);
896
897                !infcx.predicate_may_hold(&obligation)
898            }
899        {
900            cx.emit_span_lint(
901                MISSING_GENERIC_TYPE_VISITABLE_DERIVE,
902                item.span,
903                MissingGenericTypeVisitableDeriveDiag,
904            );
905        }
906    }
907}