1use rustc_hir::def::Res;
5use rustc_hir::def_id::DefId;
6use rustc_hir::{Expr, ExprKind, HirId};
7use rustc_middle::ty::{self, GenericArgsRef, PredicatePolarity, Ty};
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, TypeIrDirectUse,
18 TypeIrInherentUsage, TypeIrTraitUsage, UntranslatableDiag,
19};
20use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
21
22declare_tool_lint! {
23 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 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
59declare_tool_lint! {
60 pub rustc::POTENTIAL_QUERY_INSTABILITY,
67 Allow,
68 "require explicit opt-in when using potentially unstable methods or functions",
69 report_in_external_macro: true
70}
71
72declare_tool_lint! {
73 pub rustc::UNTRACKED_QUERY_INFORMATION,
78 Allow,
79 "require explicit opt-in when accessing information not tracked by the query system",
80 report_in_external_macro: true
81}
82
83declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]);
84
85impl<'tcx> LateLintPass<'tcx> for QueryStability {
86 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
87 if let Some((callee_def_id, span, generic_args, _recv, _args)) =
88 get_callee_span_generic_args_and_args(cx, expr)
89 && let Ok(Some(instance)) =
90 ty::Instance::try_resolve(cx.tcx, cx.typing_env(), callee_def_id, generic_args)
91 {
92 let def_id = instance.def_id();
93 if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) {
94 cx.emit_span_lint(
95 POTENTIAL_QUERY_INSTABILITY,
96 span,
97 QueryInstability { query: cx.tcx.item_name(def_id) },
98 );
99 } else if has_unstable_into_iter_predicate(cx, callee_def_id, generic_args) {
100 let call_span = span.with_hi(expr.span.hi());
101 cx.emit_span_lint(
102 POTENTIAL_QUERY_INSTABILITY,
103 call_span,
104 QueryInstability { query: sym::into_iter },
105 );
106 }
107
108 if cx.tcx.has_attr(def_id, sym::rustc_lint_untracked_query_information) {
109 cx.emit_span_lint(
110 UNTRACKED_QUERY_INFORMATION,
111 span,
112 QueryUntracked { method: cx.tcx.item_name(def_id) },
113 );
114 }
115 }
116 }
117}
118
119fn has_unstable_into_iter_predicate<'tcx>(
120 cx: &LateContext<'tcx>,
121 callee_def_id: DefId,
122 generic_args: GenericArgsRef<'tcx>,
123) -> bool {
124 let Some(into_iterator_def_id) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else {
125 return false;
126 };
127 let Some(into_iter_fn_def_id) = cx.tcx.lang_items().into_iter_fn() else {
128 return false;
129 };
130 let predicates = cx.tcx.predicates_of(callee_def_id).instantiate(cx.tcx, generic_args);
131 for (predicate, _) in predicates {
132 let Some(trait_pred) = predicate.as_trait_clause() else {
133 continue;
134 };
135 if trait_pred.def_id() != into_iterator_def_id
136 || trait_pred.polarity() != PredicatePolarity::Positive
137 {
138 continue;
139 }
140 let into_iter_fn_args =
142 cx.tcx.instantiate_bound_regions_with_erased(trait_pred).trait_ref.args;
143 let Ok(Some(instance)) = ty::Instance::try_resolve(
144 cx.tcx,
145 cx.typing_env(),
146 into_iter_fn_def_id,
147 into_iter_fn_args,
148 ) else {
149 continue;
150 };
151 if cx.tcx.has_attr(instance.def_id(), sym::rustc_lint_query_instability) {
154 return true;
155 }
156 }
157 false
158}
159
160fn get_callee_span_generic_args_and_args<'tcx>(
164 cx: &LateContext<'tcx>,
165 expr: &'tcx Expr<'tcx>,
166) -> Option<(DefId, Span, GenericArgsRef<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> {
167 if let ExprKind::Call(callee, args) = expr.kind
168 && let callee_ty = cx.typeck_results().expr_ty(callee)
169 && let ty::FnDef(callee_def_id, generic_args) = callee_ty.kind()
170 {
171 return Some((*callee_def_id, callee.span, generic_args, None, args));
172 }
173 if let ExprKind::MethodCall(segment, recv, args, _) = expr.kind
174 && let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id)
175 {
176 let generic_args = cx.typeck_results().node_args(expr.hir_id);
177 return Some((method_def_id, segment.ident.span, generic_args, Some(recv), args));
178 }
179 None
180}
181
182declare_tool_lint! {
183 pub rustc::USAGE_OF_TY_TYKIND,
186 Allow,
187 "usage of `ty::TyKind` outside of the `ty::sty` module",
188 report_in_external_macro: true
189}
190
191declare_tool_lint! {
192 pub rustc::USAGE_OF_QUALIFIED_TY,
195 Allow,
196 "using `ty::{Ty,TyCtxt}` instead of importing it",
197 report_in_external_macro: true
198}
199
200declare_lint_pass!(TyTyKind => [
201 USAGE_OF_TY_TYKIND,
202 USAGE_OF_QUALIFIED_TY,
203]);
204
205impl<'tcx> LateLintPass<'tcx> for TyTyKind {
206 fn check_path(
207 &mut self,
208 cx: &LateContext<'tcx>,
209 path: &rustc_hir::Path<'tcx>,
210 _: rustc_hir::HirId,
211 ) {
212 if let Some(segment) = path.segments.iter().nth_back(1)
213 && lint_ty_kind_usage(cx, &segment.res)
214 {
215 let span =
216 path.span.with_hi(segment.args.map_or(segment.ident.span, |a| a.span_ext).hi());
217 cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind { suggestion: span });
218 }
219 }
220
221 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx, hir::AmbigArg>) {
222 match &ty.kind {
223 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => {
224 if lint_ty_kind_usage(cx, &path.res) {
225 let span = match cx.tcx.parent_hir_node(ty.hir_id) {
226 hir::Node::PatExpr(hir::PatExpr {
227 kind: hir::PatExprKind::Path(qpath),
228 ..
229 })
230 | hir::Node::Pat(hir::Pat {
231 kind:
232 hir::PatKind::TupleStruct(qpath, ..) | hir::PatKind::Struct(qpath, ..),
233 ..
234 })
235 | hir::Node::Expr(
236 hir::Expr { kind: hir::ExprKind::Path(qpath), .. }
237 | &hir::Expr { kind: hir::ExprKind::Struct(qpath, ..), .. },
238 ) => {
239 if let hir::QPath::TypeRelative(qpath_ty, ..) = qpath
240 && qpath_ty.hir_id == ty.hir_id
241 {
242 Some(path.span)
243 } else {
244 None
245 }
246 }
247 _ => None,
248 };
249
250 match span {
251 Some(span) => {
252 cx.emit_span_lint(
253 USAGE_OF_TY_TYKIND,
254 path.span,
255 TykindKind { suggestion: span },
256 );
257 }
258 None => cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
259 }
260 } else if !ty.span.from_expansion()
261 && path.segments.len() > 1
262 && let Some(ty) = is_ty_or_ty_ctxt(cx, path)
263 {
264 cx.emit_span_lint(
265 USAGE_OF_QUALIFIED_TY,
266 path.span,
267 TyQualified { ty, suggestion: path.span },
268 );
269 }
270 }
271 _ => {}
272 }
273 }
274}
275
276fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
277 if let Some(did) = res.opt_def_id() {
278 cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
279 } else {
280 false
281 }
282}
283
284fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &hir::Path<'_>) -> Option<String> {
285 match &path.res {
286 Res::Def(_, def_id) => {
287 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
288 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
289 }
290 }
291 Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
293 if let ty::Adt(adt, args) = cx.tcx.type_of(did).instantiate_identity().kind()
294 && let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
295 {
296 return Some(format!("{}<{}>", name, args[0]));
297 }
298 }
299 _ => (),
300 }
301
302 None
303}
304
305fn gen_args(segment: &hir::PathSegment<'_>) -> String {
306 if let Some(args) = &segment.args {
307 let lifetimes = args
308 .args
309 .iter()
310 .filter_map(|arg| {
311 if let hir::GenericArg::Lifetime(lt) = arg {
312 Some(lt.ident.to_string())
313 } else {
314 None
315 }
316 })
317 .collect::<Vec<_>>();
318
319 if !lifetimes.is_empty() {
320 return format!("<{}>", lifetimes.join(", "));
321 }
322 }
323
324 String::new()
325}
326
327declare_tool_lint! {
328 pub rustc::NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
331 Allow,
332 "non-glob import of `rustc_type_ir::inherent`",
333 report_in_external_macro: true
334}
335
336declare_tool_lint! {
337 pub rustc::USAGE_OF_TYPE_IR_INHERENT,
341 Allow,
342 "usage `rustc_type_ir::inherent` outside of trait system",
343 report_in_external_macro: true
344}
345
346declare_tool_lint! {
347 pub rustc::USAGE_OF_TYPE_IR_TRAITS,
354 Allow,
355 "usage `rustc_type_ir`-specific abstraction traits outside of trait system",
356 report_in_external_macro: true
357}
358declare_tool_lint! {
359 pub rustc::DIRECT_USE_OF_RUSTC_TYPE_IR,
364 Allow,
365 "usage `rustc_type_ir` abstraction outside of trait system",
366 report_in_external_macro: true
367}
368
369declare_lint_pass!(TypeIr => [DIRECT_USE_OF_RUSTC_TYPE_IR, NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_INHERENT, USAGE_OF_TYPE_IR_TRAITS]);
370
371impl<'tcx> LateLintPass<'tcx> for TypeIr {
372 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
373 let res_def_id = match expr.kind {
374 hir::ExprKind::Path(hir::QPath::Resolved(_, path)) => path.res.opt_def_id(),
375 hir::ExprKind::Path(hir::QPath::TypeRelative(..)) | hir::ExprKind::MethodCall(..) => {
376 cx.typeck_results().type_dependent_def_id(expr.hir_id)
377 }
378 _ => return,
379 };
380 let Some(res_def_id) = res_def_id else {
381 return;
382 };
383 if let Some(assoc_item) = cx.tcx.opt_associated_item(res_def_id)
384 && let Some(trait_def_id) = assoc_item.trait_container(cx.tcx)
385 && (cx.tcx.is_diagnostic_item(sym::type_ir_interner, trait_def_id)
386 | cx.tcx.is_diagnostic_item(sym::type_ir_infer_ctxt_like, trait_def_id))
387 {
388 cx.emit_span_lint(USAGE_OF_TYPE_IR_TRAITS, expr.span, TypeIrTraitUsage);
389 }
390 }
391
392 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
393 let rustc_hir::ItemKind::Use(path, kind) = item.kind else { return };
394
395 let is_mod_inherent = |res: Res| {
396 res.opt_def_id()
397 .is_some_and(|def_id| cx.tcx.is_diagnostic_item(sym::type_ir_inherent, def_id))
398 };
399
400 if let Some(seg) = path.segments.iter().find(|seg| is_mod_inherent(seg.res)) {
402 cx.emit_span_lint(USAGE_OF_TYPE_IR_INHERENT, seg.ident.span, TypeIrInherentUsage);
403 }
404 else if let Some(type_ns) = path.res.type_ns
406 && is_mod_inherent(type_ns)
407 {
408 cx.emit_span_lint(
409 USAGE_OF_TYPE_IR_INHERENT,
410 path.segments.last().unwrap().ident.span,
411 TypeIrInherentUsage,
412 );
413 }
414
415 let (lo, hi, snippet) = match path.segments {
416 [.., penultimate, segment] if is_mod_inherent(penultimate.res) => {
417 (segment.ident.span, item.kind.ident().unwrap().span, "*")
418 }
419 [.., segment]
420 if let Some(type_ns) = path.res.type_ns
421 && is_mod_inherent(type_ns)
422 && let rustc_hir::UseKind::Single(ident) = kind =>
423 {
424 let (lo, snippet) =
425 match cx.tcx.sess.source_map().span_to_snippet(path.span).as_deref() {
426 Ok("self") => (path.span, "*"),
427 _ => (segment.ident.span.shrink_to_hi(), "::*"),
428 };
429 (lo, if segment.ident == ident { lo } else { ident.span }, snippet)
430 }
431 _ => return,
432 };
433 cx.emit_span_lint(
434 NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT,
435 path.span,
436 NonGlobImportTypeIrInherent { suggestion: lo.eq_ctxt(hi).then(|| lo.to(hi)), snippet },
437 );
438 }
439
440 fn check_path(
441 &mut self,
442 cx: &LateContext<'tcx>,
443 path: &rustc_hir::Path<'tcx>,
444 _: rustc_hir::HirId,
445 ) {
446 if let Some(seg) = path.segments.iter().find(|seg| {
447 seg.res
448 .opt_def_id()
449 .is_some_and(|def_id| cx.tcx.is_diagnostic_item(sym::type_ir, def_id))
450 }) {
451 cx.emit_span_lint(DIRECT_USE_OF_RUSTC_TYPE_IR, seg.ident.span, TypeIrDirectUse);
452 }
453 }
454}
455
456declare_tool_lint! {
457 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
460 Allow,
461 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
462}
463
464declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
465
466impl EarlyLintPass for LintPassImpl {
467 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
468 if let ast::ItemKind::Impl(ast::Impl { of_trait: Some(of_trait), .. }) = &item.kind
469 && let Some(last) = of_trait.trait_ref.path.segments.last()
470 && last.ident.name == sym::LintPass
471 {
472 let expn_data = of_trait.trait_ref.path.span.ctxt().outer_expn_data();
473 let call_site = expn_data.call_site;
474 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
475 && call_site.ctxt().outer_expn_data().kind
476 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
477 {
478 cx.emit_span_lint(
479 LINT_PASS_IMPL_WITHOUT_MACRO,
480 of_trait.trait_ref.path.span,
481 LintPassByHand,
482 );
483 }
484 }
485 }
486}
487
488declare_tool_lint! {
489 pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
495 Allow,
496 "prevent creation of diagnostics which cannot be translated",
497 report_in_external_macro: true,
498 @eval_always = true
499}
500
501declare_tool_lint! {
502 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
509 Allow,
510 "prevent diagnostic creation outside of `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls",
511 report_in_external_macro: true,
512 @eval_always = true
513}
514
515declare_lint_pass!(Diagnostics => [UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL]);
516
517impl LateLintPass<'_> for Diagnostics {
518 fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
519 let collect_args_tys_and_spans = |args: &[hir::Expr<'_>], reserve_one_extra: bool| {
520 let mut result = Vec::with_capacity(args.len() + usize::from(reserve_one_extra));
521 result.extend(args.iter().map(|arg| (cx.typeck_results().expr_ty(arg), arg.span)));
522 result
523 };
524 let Some((def_id, span, fn_gen_args, recv, args)) =
526 get_callee_span_generic_args_and_args(cx, expr)
527 else {
528 return;
529 };
530 let mut arg_tys_and_spans = collect_args_tys_and_spans(args, recv.is_some());
531 if let Some(recv) = recv {
532 arg_tys_and_spans.insert(0, (cx.tcx.types.self_param, recv.span)); }
534
535 Self::diagnostic_outside_of_impl(cx, span, expr.hir_id, def_id, fn_gen_args);
536 Self::untranslatable_diagnostic(cx, def_id, &arg_tys_and_spans);
537 }
538}
539
540impl Diagnostics {
541 fn is_diag_message<'cx>(cx: &LateContext<'cx>, ty: Ty<'cx>) -> bool {
543 if let Some(adt_def) = ty.ty_adt_def()
544 && let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did())
545 && matches!(name, sym::DiagMessage | sym::SubdiagMessage)
546 {
547 true
548 } else {
549 false
550 }
551 }
552
553 fn untranslatable_diagnostic<'cx>(
554 cx: &LateContext<'cx>,
555 def_id: DefId,
556 arg_tys_and_spans: &[(Ty<'cx>, Span)],
557 ) {
558 let fn_sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_binder();
559 let predicates = cx.tcx.predicates_of(def_id).instantiate_identity(cx.tcx).predicates;
560 for (i, ¶m_ty) in fn_sig.inputs().iter().enumerate() {
561 if let ty::Param(sig_param) = param_ty.kind() {
562 for pred in predicates.iter() {
564 if let Some(trait_pred) = pred.as_trait_clause()
565 && let trait_ref = trait_pred.skip_binder().trait_ref
566 && trait_ref.self_ty() == param_ty && cx.tcx.is_diagnostic_item(sym::Into, trait_ref.def_id)
568 && let ty1 = trait_ref.args.type_at(1)
569 && Self::is_diag_message(cx, ty1)
570 {
571 let (arg_ty, arg_span) = arg_tys_and_spans[i];
575
576 let is_translatable = Self::is_diag_message(cx, arg_ty)
578 || matches!(arg_ty.kind(), ty::Param(arg_param) if arg_param.name == sig_param.name);
579 if !is_translatable {
580 cx.emit_span_lint(
581 UNTRANSLATABLE_DIAGNOSTIC,
582 arg_span,
583 UntranslatableDiag,
584 );
585 }
586 }
587 }
588 }
589 }
590 }
591
592 fn diagnostic_outside_of_impl<'cx>(
593 cx: &LateContext<'cx>,
594 span: Span,
595 current_id: HirId,
596 def_id: DefId,
597 fn_gen_args: GenericArgsRef<'cx>,
598 ) {
599 let Some(inst) =
601 ty::Instance::try_resolve(cx.tcx, cx.typing_env(), def_id, fn_gen_args).ok().flatten()
602 else {
603 return;
604 };
605 let has_attr = cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics);
606 if !has_attr {
607 return;
608 };
609
610 for (hir_id, _parent) in cx.tcx.hir_parent_iter(current_id) {
611 if let Some(owner_did) = hir_id.as_owner()
612 && cx.tcx.has_attr(owner_did, sym::rustc_lint_diagnostics)
613 {
614 return;
616 }
617 }
618
619 let mut is_inside_appropriate_impl = false;
625 for (_hir_id, parent) in cx.tcx.hir_parent_iter(current_id) {
626 debug!(?parent);
627 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) = parent
628 && let Some(of_trait) = impl_.of_trait
629 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
630 && let Some(name) = cx.tcx.get_diagnostic_name(def_id)
631 && matches!(name, sym::Diagnostic | sym::Subdiagnostic | sym::LintDiagnostic)
632 {
633 is_inside_appropriate_impl = true;
634 break;
635 }
636 }
637 debug!(?is_inside_appropriate_impl);
638 if !is_inside_appropriate_impl {
639 cx.emit_span_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, DiagOutOfImpl);
640 }
641 }
642}
643
644declare_tool_lint! {
645 pub rustc::BAD_OPT_ACCESS,
648 Deny,
649 "prevent using options by field access when there is a wrapper function",
650 report_in_external_macro: true
651}
652
653declare_lint_pass!(BadOptAccess => [BAD_OPT_ACCESS]);
654
655impl LateLintPass<'_> for BadOptAccess {
656 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
657 let hir::ExprKind::Field(base, target) = expr.kind else { return };
658 let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
659 if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
662 return;
663 }
664
665 for field in adt_def.all_fields() {
666 if field.name == target.name
667 && let Some(attr) =
668 cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access)
669 && let Some(items) = attr.meta_item_list()
670 && let Some(item) = items.first()
671 && let Some(lit) = item.lit()
672 && let ast::LitKind::Str(val, _) = lit.kind
673 {
674 cx.emit_span_lint(
675 BAD_OPT_ACCESS,
676 expr.span,
677 BadOptAccessDiag { msg: val.as_str() },
678 );
679 }
680 }
681 }
682}
683
684declare_tool_lint! {
685 pub rustc::SPAN_USE_EQ_CTXT,
686 Allow,
687 "forbid uses of `==` with `Span::ctxt`, suggest `Span::eq_ctxt` instead",
688 report_in_external_macro: true
689}
690
691declare_lint_pass!(SpanUseEqCtxt => [SPAN_USE_EQ_CTXT]);
692
693impl<'tcx> LateLintPass<'tcx> for SpanUseEqCtxt {
694 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
695 if let hir::ExprKind::Binary(
696 hir::BinOp { node: hir::BinOpKind::Eq | hir::BinOpKind::Ne, .. },
697 lhs,
698 rhs,
699 ) = expr.kind
700 {
701 if is_span_ctxt_call(cx, lhs) && is_span_ctxt_call(cx, rhs) {
702 cx.emit_span_lint(SPAN_USE_EQ_CTXT, expr.span, SpanUseEqCtxtDiag);
703 }
704 }
705 }
706}
707
708fn is_span_ctxt_call(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
709 match &expr.kind {
710 hir::ExprKind::MethodCall(..) => cx
711 .typeck_results()
712 .type_dependent_def_id(expr.hir_id)
713 .is_some_and(|call_did| cx.tcx.is_diagnostic_item(sym::SpanCtxt, call_did)),
714
715 _ => false,
716 }
717}
718
719declare_tool_lint! {
720 pub rustc::SYMBOL_INTERN_STRING_LITERAL,
722 Allow,
725 "Forbid uses of string literals in `Symbol::intern`, suggesting preinterning instead",
726 report_in_external_macro: true
727}
728
729declare_lint_pass!(SymbolInternStringLiteral => [SYMBOL_INTERN_STRING_LITERAL]);
730
731impl<'tcx> LateLintPass<'tcx> for SymbolInternStringLiteral {
732 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx rustc_hir::Expr<'tcx>) {
733 if let hir::ExprKind::Call(path, [arg]) = expr.kind
734 && let hir::ExprKind::Path(ref qpath) = path.kind
735 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
736 && cx.tcx.is_diagnostic_item(sym::SymbolIntern, def_id)
737 && let hir::ExprKind::Lit(kind) = arg.kind
738 && let rustc_ast::LitKind::Str(_, _) = kind.node
739 {
740 cx.emit_span_lint(
741 SYMBOL_INTERN_STRING_LITERAL,
742 kind.span,
743 SymbolInternStringLiteralDiag,
744 );
745 }
746 }
747}