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_hir::HirId;
5use rustc_hir::def::Res;
6use rustc_hir::def_id::DefId;
7use rustc_middle::ty::{self, GenericArgsRef, Ty as MiddleTy};
8use rustc_session::{declare_lint_pass, declare_tool_lint};
9use rustc_span::hygiene::{ExpnKind, MacroKind};
10use rustc_span::{Span, sym};
11use tracing::debug;
12use {rustc_ast as ast, rustc_hir as hir};
13
14use crate::lints::{
15    BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand,
16    NonGlobImportTypeIrInherent, QueryInstability, QueryUntracked, SpanUseEqCtxtDiag,
17    SymbolInternStringLiteralDiag, TyQualified, TykindDiag, TykindKind, TypeIrInherentUsage,
18    TypeIrTraitUsage, UntranslatableDiag,
19};
20use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
21
22declare_tool_lint! {
23    /// The `default_hash_type` lint detects use of [`std::collections::HashMap`] and
24    /// [`std::collections::HashSet`], suggesting the use of `FxHashMap`/`FxHashSet`.
25    ///
26    /// This can help as `FxHasher` can perform better than the default hasher. DOS protection is
27    /// not required as input is assumed to be trusted.
28    pub rustc::DEFAULT_HASH_TYPES,
29    Allow,
30    "forbid HashMap and HashSet and suggest the FxHash* variants",
31    report_in_external_macro: true
32}
33
34declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
35
36impl LateLintPass<'_> for DefaultHashTypes {
37    fn check_path(&mut self, cx: &LateContext<'_>, path: &hir::Path<'_>, hir_id: HirId) {
38        let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
39        if matches!(
40            cx.tcx.hir_node(hir_id),
41            hir::Node::Item(hir::Item { kind: hir::ItemKind::Use(..), .. })
42        ) {
43            // Don't lint imports, only actual usages.
44            return;
45        }
46        let preferred = match cx.tcx.get_diagnostic_name(def_id) {
47            Some(sym::HashMap) => "FxHashMap",
48            Some(sym::HashSet) => "FxHashSet",
49            _ => return,
50        };
51        cx.emit_span_lint(
52            DEFAULT_HASH_TYPES,
53            path.span,
54            DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) },
55        );
56    }
57}
58
59/// Helper function for lints that check for expressions with calls and use typeck results to
60/// get the `DefId` and `GenericArgsRef` of the function.
61fn typeck_results_of_method_fn<'tcx>(
62    cx: &LateContext<'tcx>,
63    expr: &hir::Expr<'_>,
64) -> Option<(Span, DefId, ty::GenericArgsRef<'tcx>)> {
65    match expr.kind {
66        hir::ExprKind::MethodCall(segment, ..)
67            if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
68        {
69            Some((segment.ident.span, def_id, cx.typeck_results().node_args(expr.hir_id)))
70        }
71        _ => match cx.typeck_results().node_type(expr.hir_id).kind() {
72            &ty::FnDef(def_id, args) => Some((expr.span, def_id, args)),
73            _ => None,
74        },
75    }
76}
77
78declare_tool_lint! {
79    /// The `potential_query_instability` lint detects use of methods which can lead to
80    /// potential query instability, such as iterating over a `HashMap`.
81    ///
82    /// Due to the [incremental compilation](https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation.html) model,
83    /// queries must return deterministic, stable results. `HashMap` iteration order can change
84    /// between compilations, and will introduce instability if query results expose the order.
85    pub rustc::POTENTIAL_QUERY_INSTABILITY,
86    Allow,
87    "require explicit opt-in when using potentially unstable methods or functions",
88    report_in_external_macro: true
89}
90
91declare_tool_lint! {
92    /// The `untracked_query_information` lint detects use of methods which leak information not
93    /// tracked by the query system, such as whether a `Steal<T>` value has already been stolen. In
94    /// order not to break incremental compilation, such methods must be used very carefully or not
95    /// at all.
96    pub rustc::UNTRACKED_QUERY_INFORMATION,
97    Allow,
98    "require explicit opt-in when accessing information not tracked by the query system",
99    report_in_external_macro: true
100}
101
102declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]);
103
104impl LateLintPass<'_> for QueryStability {
105    fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
106        let Some((span, def_id, args)) = typeck_results_of_method_fn(cx, expr) else { return };
107        if let Ok(Some(instance)) = ty::Instance::try_resolve(cx.tcx, cx.typing_env(), def_id, args)
108        {
109            let def_id = instance.def_id();
110            if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) {
111                cx.emit_span_lint(
112                    POTENTIAL_QUERY_INSTABILITY,
113                    span,
114                    QueryInstability { query: cx.tcx.item_name(def_id) },
115                );
116            }
117            if cx.tcx.has_attr(def_id, sym::rustc_lint_untracked_query_information) {
118                cx.emit_span_lint(
119                    UNTRACKED_QUERY_INFORMATION,
120                    span,
121                    QueryUntracked { method: cx.tcx.item_name(def_id) },
122                );
123            }
124        }
125    }
126}
127
128declare_tool_lint! {
129    /// The `usage_of_ty_tykind` lint detects usages of `ty::TyKind::<kind>`,
130    /// where `ty::<kind>` would suffice.
131    pub rustc::USAGE_OF_TY_TYKIND,
132    Allow,
133    "usage of `ty::TyKind` outside of the `ty::sty` module",
134    report_in_external_macro: true
135}
136
137declare_tool_lint! {
138    /// The `usage_of_qualified_ty` lint detects usages of `ty::TyKind`,
139    /// where `Ty` should be used instead.
140    pub rustc::USAGE_OF_QUALIFIED_TY,
141    Allow,
142    "using `ty::{Ty,TyCtxt}` instead of importing it",
143    report_in_external_macro: true
144}
145
146declare_lint_pass!(TyTyKind => [
147    USAGE_OF_TY_TYKIND,
148    USAGE_OF_QUALIFIED_TY,
149]);
150
151impl<'tcx> LateLintPass<'tcx> for TyTyKind {
152    fn check_path(
153        &mut self,
154        cx: &LateContext<'tcx>,
155        path: &rustc_hir::Path<'tcx>,
156        _: rustc_hir::HirId,
157    ) {
158        if let Some(segment) = path.segments.iter().nth_back(1)
159            && lint_ty_kind_usage(cx, &segment.res)
160        {
161            let span =
162                path.span.with_hi(segment.args.map_or(segment.ident.span, |a| a.span_ext).hi());
163            cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind { suggestion: span });
164        }
165    }
166
167    fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx, hir::AmbigArg>) {
168        match &ty.kind {
169            hir::TyKind::Path(hir::QPath::Resolved(_, path)) => {
170                if lint_ty_kind_usage(cx, &path.res) {
171                    let span = match cx.tcx.parent_hir_node(ty.hir_id) {
172                        hir::Node::PatExpr(hir::PatExpr {
173                            kind: hir::PatExprKind::Path(qpath),
174                            ..
175                        })
176                        | hir::Node::Pat(hir::Pat {
177                            kind:
178                                hir::PatKind::TupleStruct(qpath, ..) | hir::PatKind::Struct(qpath, ..),
179                            ..
180                        })
181                        | hir::Node::Expr(
182                            hir::Expr { kind: hir::ExprKind::Path(qpath), .. }
183                            | &hir::Expr { kind: hir::ExprKind::Struct(qpath, ..), .. },
184                        ) => {
185                            if let hir::QPath::TypeRelative(qpath_ty, ..) = qpath
186                                && qpath_ty.hir_id == ty.hir_id
187                            {
188                                Some(path.span)
189                            } else {
190                                None
191                            }
192                        }
193                        _ => None,
194                    };
195
196                    match span {
197                        Some(span) => {
198                            cx.emit_span_lint(
199                                USAGE_OF_TY_TYKIND,
200                                path.span,
201                                TykindKind { suggestion: span },
202                            );
203                        }
204                        None => cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
205                    }
206                } else if !ty.span.from_expansion()
207                    && path.segments.len() > 1
208                    && let Some(ty) = is_ty_or_ty_ctxt(cx, path)
209                {
210                    cx.emit_span_lint(
211                        USAGE_OF_QUALIFIED_TY,
212                        path.span,
213                        TyQualified { ty, suggestion: path.span },
214                    );
215                }
216            }
217            _ => {}
218        }
219    }
220}
221
222fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
223    if let Some(did) = res.opt_def_id() {
224        cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
225    } else {
226        false
227    }
228}
229
230fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &hir::Path<'_>) -> Option<String> {
231    match &path.res {
232        Res::Def(_, def_id) => {
233            if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
234                return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
235            }
236        }
237        // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
238        Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
239            if let ty::Adt(adt, args) = cx.tcx.type_of(did).instantiate_identity().kind()
240                && let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
241            {
242                return Some(format!("{}<{}>", name, args[0]));
243            }
244        }
245        _ => (),
246    }
247
248    None
249}
250
251fn gen_args(segment: &hir::PathSegment<'_>) -> String {
252    if let Some(args) = &segment.args {
253        let lifetimes = args
254            .args
255            .iter()
256            .filter_map(|arg| {
257                if let hir::GenericArg::Lifetime(lt) = arg {
258                    Some(lt.ident.to_string())
259                } else {
260                    None
261                }
262            })
263            .collect::<Vec<_>>();
264
265        if !lifetimes.is_empty() {
266            return format!("<{}>", lifetimes.join(", "));
267        }
268    }
269
270    String::new()
271}
272
273declare_tool_lint! {
274    /// The `non_glob_import_of_type_ir_inherent_item` lint detects
275    /// non-glob imports of module `rustc_type_ir::inherent`.
276    pub rustc::NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
277    Allow,
278    "non-glob import of `rustc_type_ir::inherent`",
279    report_in_external_macro: true
280}
281
282declare_tool_lint! {
283    /// The `usage_of_type_ir_inherent` lint detects usage of `rustc_type_ir::inherent`.
284    ///
285    /// This module should only be used within the trait solver.
286    pub rustc::USAGE_OF_TYPE_IR_INHERENT,
287    Allow,
288    "usage `rustc_type_ir::inherent` outside of trait system",
289    report_in_external_macro: true
290}
291
292declare_tool_lint! {
293    /// The `usage_of_type_ir_traits` lint detects usage of `rustc_type_ir::Interner`,
294    /// or `rustc_infer::InferCtxtLike`.
295    ///
296    /// Methods of this trait should only be used within the type system abstraction layer,
297    /// and in the generic next trait solver implementation. Look for an analogously named
298    /// method on `TyCtxt` or `InferCtxt` (respectively).
299    pub rustc::USAGE_OF_TYPE_IR_TRAITS,
300    Allow,
301    "usage `rustc_type_ir`-specific abstraction traits outside of trait system",
302    report_in_external_macro: true
303}
304
305declare_lint_pass!(TypeIr => [NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_TRAITS]);
306
307impl<'tcx> LateLintPass<'tcx> for TypeIr {
308    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
309        let res_def_id = match expr.kind {
310            hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => path.res.opt_def_id(),
311            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) | hir::ExprKind::MethodCall(..) => {
312                cx.typeck_results().type_dependent_def_id(expr.hir_id)
313            }
314            _ => return,
315        };
316        let Some(res_def_id) = res_def_id else {
317            return;
318        };
319        if let Some(assoc_item) = cx.tcx.opt_associated_item(res_def_id)
320            && let Some(trait_def_id) = assoc_item.trait_container(cx.tcx)
321            && (cx.tcx.is_diagnostic_item(sym::type_ir_interner, trait_def_id)
322                | cx.tcx.is_diagnostic_item(sym::type_ir_infer_ctxt_like, trait_def_id))
323        {
324            cx.emit_span_lint(USAGE_OF_TYPE_IR_TRAITS, expr.span, TypeIrTraitUsage);
325        }
326    }
327
328    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
329        let rustc_hir::ItemKind::Use(path, kind) = item.kind else { return };
330
331        let is_mod_inherent = |res: Res| {
332            res.opt_def_id()
333                .is_some_and(|def_id| cx.tcx.is_diagnostic_item(sym::type_ir_inherent, def_id))
334        };
335
336        // Path segments except for the final.
337        if let Some(seg) = path.segments.iter().find(|seg| is_mod_inherent(seg.res)) {
338            cx.emit_span_lint(USAGE_OF_TYPE_IR_INHERENT, seg.ident.span, TypeIrInherentUsage);
339        }
340        // Final path resolutions, like `use rustc_type_ir::inherent`
341        else if let Some(type_ns) = path.res.type_ns
342            && is_mod_inherent(type_ns)
343        {
344            cx.emit_span_lint(
345                USAGE_OF_TYPE_IR_INHERENT,
346                path.segments.last().unwrap().ident.span,
347                TypeIrInherentUsage,
348            );
349        }
350
351        let (lo, hi, snippet) = match path.segments {
352            [.., penultimate, segment] if is_mod_inherent(penultimate.res) => {
353                (segment.ident.span, item.kind.ident().unwrap().span, "*")
354            }
355            [.., segment]
356                if let Some(type_ns) = path.res.type_ns
357                    && is_mod_inherent(type_ns)
358                    && let rustc_hir::UseKind::Single(ident) = kind =>
359            {
360                let (lo, snippet) =
361                    match cx.tcx.sess.source_map().span_to_snippet(path.span).as_deref() {
362                        Ok("self") => (path.span, "*"),
363                        _ => (segment.ident.span.shrink_to_hi(), "::*"),
364                    };
365                (lo, if segment.ident == ident { lo } else { ident.span }, snippet)
366            }
367            _ => return,
368        };
369        cx.emit_span_lint(
370            NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
371            path.span,
372            NonGlobImportTypeIrInherent { suggestion: lo.eq_ctxt(hi).then(|| lo.to(hi)), snippet },
373        );
374    }
375}
376
377declare_tool_lint! {
378    /// The `lint_pass_impl_without_macro` detects manual implementations of a lint
379    /// pass, without using [`declare_lint_pass`] or [`impl_lint_pass`].
380    pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
381    Allow,
382    "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
383}
384
385declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
386
387impl EarlyLintPass for LintPassImpl {
388    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
389        if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
390            if let Some(last) = lint_pass.path.segments.last() {
391                if last.ident.name == sym::LintPass {
392                    let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
393                    let call_site = expn_data.call_site;
394                    if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
395                        && call_site.ctxt().outer_expn_data().kind
396                            != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
397                    {
398                        cx.emit_span_lint(
399                            LINT_PASS_IMPL_WITHOUT_MACRO,
400                            lint_pass.path.span,
401                            LintPassByHand,
402                        );
403                    }
404                }
405            }
406        }
407    }
408}
409
410declare_tool_lint! {
411    /// The `untranslatable_diagnostic` lint detects messages passed to functions with `impl
412    /// Into<{D,Subd}iagMessage` parameters without using translatable Fluent strings.
413    ///
414    /// More details on translatable diagnostics can be found
415    /// [here](https://rustc-dev-guide.rust-lang.org/diagnostics/translation.html).
416    pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
417    Allow,
418    "prevent creation of diagnostics which cannot be translated",
419    report_in_external_macro: true,
420    @eval_always = true
421}
422
423declare_tool_lint! {
424    /// The `diagnostic_outside_of_impl` lint detects calls to functions annotated with
425    /// `#[rustc_lint_diagnostics]` that are outside an `Diagnostic`, `Subdiagnostic`, or
426    /// `LintDiagnostic` impl (either hand-written or derived).
427    ///
428    /// More details on diagnostics implementations can be found
429    /// [here](https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html).
430    pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
431    Allow,
432    "prevent diagnostic creation outside of `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls",
433    report_in_external_macro: true,
434    @eval_always = true
435}
436
437declare_lint_pass!(Diagnostics => [UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL]);
438
439impl LateLintPass<'_> for Diagnostics {
440    fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
441        let collect_args_tys_and_spans = |args: &[hir::Expr<'_>], reserve_one_extra: bool| {
442            let mut result = Vec::with_capacity(args.len() + usize::from(reserve_one_extra));
443            result.extend(args.iter().map(|arg| (cx.typeck_results().expr_ty(arg), arg.span)));
444            result
445        };
446        // Only check function calls and method calls.
447        let (span, def_id, fn_gen_args, arg_tys_and_spans) = match expr.kind {
448            hir::ExprKind::Call(callee, args) => {
449                match cx.typeck_results().node_type(callee.hir_id).kind() {
450                    &ty::FnDef(def_id, fn_gen_args) => {
451                        (callee.span, def_id, fn_gen_args, collect_args_tys_and_spans(args, false))
452                    }
453                    _ => return, // occurs for fns passed as args
454                }
455            }
456            hir::ExprKind::MethodCall(_segment, _recv, args, _span) => {
457                let Some((span, def_id, fn_gen_args)) = typeck_results_of_method_fn(cx, expr)
458                else {
459                    return;
460                };
461                let mut args = collect_args_tys_and_spans(args, true);
462                args.insert(0, (cx.tcx.types.self_param, _recv.span)); // dummy inserted for `self`
463                (span, def_id, fn_gen_args, args)
464            }
465            _ => return,
466        };
467
468        Self::diagnostic_outside_of_impl(cx, span, expr.hir_id, def_id, fn_gen_args);
469        Self::untranslatable_diagnostic(cx, def_id, &arg_tys_and_spans);
470    }
471}
472
473impl Diagnostics {
474    // Is the type `{D,Subd}iagMessage`?
475    fn is_diag_message<'cx>(cx: &LateContext<'cx>, ty: MiddleTy<'cx>) -> bool {
476        if let Some(adt_def) = ty.ty_adt_def()
477            && let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did())
478            && matches!(name, sym::DiagMessage | sym::SubdiagMessage)
479        {
480            true
481        } else {
482            false
483        }
484    }
485
486    fn untranslatable_diagnostic<'cx>(
487        cx: &LateContext<'cx>,
488        def_id: DefId,
489        arg_tys_and_spans: &[(MiddleTy<'cx>, Span)],
490    ) {
491        let fn_sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_binder();
492        let predicates = cx.tcx.predicates_of(def_id).instantiate_identity(cx.tcx).predicates;
493        for (i, &param_ty) in fn_sig.inputs().iter().enumerate() {
494            if let ty::Param(sig_param) = param_ty.kind() {
495                // It is a type parameter. Check if it is `impl Into<{D,Subd}iagMessage>`.
496                for pred in predicates.iter() {
497                    if let Some(trait_pred) = pred.as_trait_clause()
498                        && let trait_ref = trait_pred.skip_binder().trait_ref
499                        && trait_ref.self_ty() == param_ty // correct predicate for the param?
500                        && cx.tcx.is_diagnostic_item(sym::Into, trait_ref.def_id)
501                        && let ty1 = trait_ref.args.type_at(1)
502                        && Self::is_diag_message(cx, ty1)
503                    {
504                        // Calls to methods with an `impl Into<{D,Subd}iagMessage>` parameter must be passed an arg
505                        // with type `{D,Subd}iagMessage` or `impl Into<{D,Subd}iagMessage>`. Otherwise, emit an
506                        // `UNTRANSLATABLE_DIAGNOSTIC` lint.
507                        let (arg_ty, arg_span) = arg_tys_and_spans[i];
508
509                        // Is the arg type `{Sub,D}iagMessage`or `impl Into<{Sub,D}iagMessage>`?
510                        let is_translatable = Self::is_diag_message(cx, arg_ty)
511                            || matches!(arg_ty.kind(), ty::Param(arg_param) if arg_param.name == sig_param.name);
512                        if !is_translatable {
513                            cx.emit_span_lint(
514                                UNTRANSLATABLE_DIAGNOSTIC,
515                                arg_span,
516                                UntranslatableDiag,
517                            );
518                        }
519                    }
520                }
521            }
522        }
523    }
524
525    fn diagnostic_outside_of_impl<'cx>(
526        cx: &LateContext<'cx>,
527        span: Span,
528        current_id: HirId,
529        def_id: DefId,
530        fn_gen_args: GenericArgsRef<'cx>,
531    ) {
532        // Is the callee marked with `#[rustc_lint_diagnostics]`?
533        let Some(inst) =
534            ty::Instance::try_resolve(cx.tcx, cx.typing_env(), def_id, fn_gen_args).ok().flatten()
535        else {
536            return;
537        };
538        let has_attr = cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics);
539        if !has_attr {
540            return;
541        };
542
543        for (hir_id, _parent) in cx.tcx.hir_parent_iter(current_id) {
544            if let Some(owner_did) = hir_id.as_owner()
545                && cx.tcx.has_attr(owner_did, sym::rustc_lint_diagnostics)
546            {
547                // The parent method is marked with `#[rustc_lint_diagnostics]`
548                return;
549            }
550        }
551
552        // Calls to `#[rustc_lint_diagnostics]`-marked functions should only occur:
553        // - inside an impl of `Diagnostic`, `Subdiagnostic`, or `LintDiagnostic`, or
554        // - inside a parent function that is itself marked with `#[rustc_lint_diagnostics]`.
555        //
556        // Otherwise, emit a `DIAGNOSTIC_OUTSIDE_OF_IMPL` lint.
557        let mut is_inside_appropriate_impl = false;
558        for (_hir_id, parent) in cx.tcx.hir_parent_iter(current_id) {
559            debug!(?parent);
560            if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) = parent
561                && let hir::Impl { of_trait: Some(of_trait), .. } = impl_
562                && let Some(def_id) = of_trait.trait_def_id()
563                && let Some(name) = cx.tcx.get_diagnostic_name(def_id)
564                && matches!(name, sym::Diagnostic | sym::Subdiagnostic | sym::LintDiagnostic)
565            {
566                is_inside_appropriate_impl = true;
567                break;
568            }
569        }
570        debug!(?is_inside_appropriate_impl);
571        if !is_inside_appropriate_impl {
572            cx.emit_span_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, DiagOutOfImpl);
573        }
574    }
575}
576
577declare_tool_lint! {
578    /// The `bad_opt_access` lint detects accessing options by field instead of
579    /// the wrapper function.
580    pub rustc::BAD_OPT_ACCESS,
581    Deny,
582    "prevent using options by field access when there is a wrapper function",
583    report_in_external_macro: true
584}
585
586declare_lint_pass!(BadOptAccess => [BAD_OPT_ACCESS]);
587
588impl LateLintPass<'_> for BadOptAccess {
589    fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
590        let hir::ExprKind::Field(base, target) = expr.kind else { return };
591        let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
592        // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
593        // avoided.
594        if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
595            return;
596        }
597
598        for field in adt_def.all_fields() {
599            if field.name == target.name
600                && let Some(attr) =
601                    cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access)
602                && let Some(items) = attr.meta_item_list()
603                && let Some(item) = items.first()
604                && let Some(lit) = item.lit()
605                && let ast::LitKind::Str(val, _) = lit.kind
606            {
607                cx.emit_span_lint(
608                    BAD_OPT_ACCESS,
609                    expr.span,
610                    BadOptAccessDiag { msg: val.as_str() },
611                );
612            }
613        }
614    }
615}
616
617declare_tool_lint! {
618    pub rustc::SPAN_USE_EQ_CTXT,
619    Allow,
620    "forbid uses of `==` with `Span::ctxt`, suggest `Span::eq_ctxt` instead",
621    report_in_external_macro: true
622}
623
624declare_lint_pass!(SpanUseEqCtxt => [SPAN_USE_EQ_CTXT]);
625
626impl<'tcx> LateLintPass<'tcx> for SpanUseEqCtxt {
627    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
628        if let hir::ExprKind::Binary(
629            hir::BinOp { node: hir::BinOpKind::Eq | hir::BinOpKind::Ne, .. },
630            lhs,
631            rhs,
632        ) = expr.kind
633        {
634            if is_span_ctxt_call(cx, lhs) && is_span_ctxt_call(cx, rhs) {
635                cx.emit_span_lint(SPAN_USE_EQ_CTXT, expr.span, SpanUseEqCtxtDiag);
636            }
637        }
638    }
639}
640
641fn is_span_ctxt_call(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
642    match &expr.kind {
643        hir::ExprKind::MethodCall(..) => cx
644            .typeck_results()
645            .type_dependent_def_id(expr.hir_id)
646            .is_some_and(|call_did| cx.tcx.is_diagnostic_item(sym::SpanCtxt, call_did)),
647
648        _ => false,
649    }
650}
651
652declare_tool_lint! {
653    /// The `symbol_intern_string_literal` detects `Symbol::intern` being called on a string literal
654    pub rustc::SYMBOL_INTERN_STRING_LITERAL,
655    // rustc_driver crates out of the compiler can't/shouldn't add preinterned symbols;
656    // bootstrap will deny this manually
657    Allow,
658    "Forbid uses of string literals in `Symbol::intern`, suggesting preinterning instead",
659    report_in_external_macro: true
660}
661
662declare_lint_pass!(SymbolInternStringLiteral => [SYMBOL_INTERN_STRING_LITERAL]);
663
664impl<'tcx> LateLintPass<'tcx> for SymbolInternStringLiteral {
665    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) {
666        if let hir::ExprKind::Call(path, [arg]) = expr.kind
667            && let hir::ExprKind::Path(ref qpath) = path.kind
668            && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
669            && cx.tcx.is_diagnostic_item(sym::SymbolIntern, def_id)
670            && let hir::ExprKind::Lit(kind) = arg.kind
671            && let rustc_ast::LitKind::Str(_, _) = kind.node
672        {
673            cx.emit_span_lint(
674                SYMBOL_INTERN_STRING_LITERAL,
675                kind.span,
676                SymbolInternStringLiteralDiag,
677            );
678        }
679    }
680}