• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Some lints that are only useful in the compiler or crates that use compiler internals, such as
2 //! Clippy.
3 
4 use crate::lints::{
5     BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand, NonExistentDocKeyword,
6     QueryInstability, TyQualified, TykindDiag, TykindKind, UntranslatableDiag,
7     UntranslatableDiagnosticTrivial,
8 };
9 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
10 use rustc_ast as ast;
11 use rustc_hir::def::Res;
12 use rustc_hir::{def_id::DefId, Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath};
13 use rustc_hir::{HirId, Impl, Item, ItemKind, Node, Pat, Ty, TyKind};
14 use rustc_middle::ty;
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::hygiene::{ExpnKind, MacroKind};
17 use rustc_span::symbol::{kw, sym, Symbol};
18 use rustc_span::Span;
19 
20 declare_tool_lint! {
21     /// The `default_hash_type` lint detects use of [`std::collections::HashMap`]/[`std::collections::HashSet`],
22     /// suggesting the use of `FxHashMap`/`FxHashSet`.
23     ///
24     /// This can help as `FxHasher` can perform better than the default hasher. DOS protection is not
25     /// required as input is assumed to be trusted.
26     pub rustc::DEFAULT_HASH_TYPES,
27     Allow,
28     "forbid HashMap and HashSet and suggest the FxHash* variants",
29     report_in_external_macro: true
30 }
31 
32 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
33 
34 impl LateLintPass<'_> for DefaultHashTypes {
check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId)35     fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
36         let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
37         if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
38             // don't lint imports, only actual usages
39             return;
40         }
41         let preferred = match cx.tcx.get_diagnostic_name(def_id) {
42             Some(sym::HashMap) => "FxHashMap",
43             Some(sym::HashSet) => "FxHashSet",
44             _ => return,
45         };
46         cx.emit_spanned_lint(
47             DEFAULT_HASH_TYPES,
48             path.span,
49             DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) },
50         );
51     }
52 }
53 
54 /// Helper function for lints that check for expressions with calls and use typeck results to
55 /// get the `DefId` and `SubstsRef` of the function.
typeck_results_of_method_fn<'tcx>( cx: &LateContext<'tcx>, expr: &Expr<'_>, ) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)>56 fn typeck_results_of_method_fn<'tcx>(
57     cx: &LateContext<'tcx>,
58     expr: &Expr<'_>,
59 ) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)> {
60     match expr.kind {
61         ExprKind::MethodCall(segment, ..)
62             if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
63         {
64             Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
65         },
66         _ => {
67             match cx.typeck_results().node_type(expr.hir_id).kind() {
68                 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
69                 _ => None,
70             }
71         }
72     }
73 }
74 
75 declare_tool_lint! {
76     /// The `potential_query_instability` lint detects use of methods which can lead to
77     /// potential query instability, such as iterating over a `HashMap`.
78     ///
79     /// Due to the [incremental compilation](https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation.html) model,
80     /// queries must return deterministic, stable results. `HashMap` iteration order can change between compilations,
81     /// and will introduce instability if query results expose the order.
82     pub rustc::POTENTIAL_QUERY_INSTABILITY,
83     Allow,
84     "require explicit opt-in when using potentially unstable methods or functions",
85     report_in_external_macro: true
86 }
87 
88 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
89 
90 impl LateLintPass<'_> for QueryStability {
check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>)91     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
92         let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
93         if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) {
94             let def_id = instance.def_id();
95             if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) {
96                 cx.emit_spanned_lint(
97                     POTENTIAL_QUERY_INSTABILITY,
98                     span,
99                     QueryInstability { query: cx.tcx.item_name(def_id) },
100                 );
101             }
102         }
103     }
104 }
105 
106 declare_tool_lint! {
107     /// The `usage_of_ty_tykind` lint detects usages of `ty::TyKind::<kind>`,
108     /// where `ty::<kind>` would suffice.
109     pub rustc::USAGE_OF_TY_TYKIND,
110     Allow,
111     "usage of `ty::TyKind` outside of the `ty::sty` module",
112     report_in_external_macro: true
113 }
114 
115 declare_tool_lint! {
116     /// The `usage_of_qualified_ty` lint detects usages of `ty::TyKind`,
117     /// where `Ty` should be used instead.
118     pub rustc::USAGE_OF_QUALIFIED_TY,
119     Allow,
120     "using `ty::{Ty,TyCtxt}` instead of importing it",
121     report_in_external_macro: true
122 }
123 
124 declare_lint_pass!(TyTyKind => [
125     USAGE_OF_TY_TYKIND,
126     USAGE_OF_QUALIFIED_TY,
127 ]);
128 
129 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
check_path( &mut self, cx: &LateContext<'tcx>, path: &rustc_hir::Path<'tcx>, _: rustc_hir::HirId, )130     fn check_path(
131         &mut self,
132         cx: &LateContext<'tcx>,
133         path: &rustc_hir::Path<'tcx>,
134         _: rustc_hir::HirId,
135     ) {
136         if let Some(segment) = path.segments.iter().nth_back(1)
137         && lint_ty_kind_usage(cx, &segment.res)
138         {
139             let span = path.span.with_hi(
140                 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
141             );
142             cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
143                 suggestion: span,
144             });
145         }
146     }
147 
check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>)148     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
149         match &ty.kind {
150             TyKind::Path(QPath::Resolved(_, path)) => {
151                 if lint_ty_kind_usage(cx, &path.res) {
152                     let hir = cx.tcx.hir();
153                     let span = match hir.find_parent(ty.hir_id) {
154                         Some(Node::Pat(Pat {
155                             kind:
156                                 PatKind::Path(qpath)
157                                 | PatKind::TupleStruct(qpath, ..)
158                                 | PatKind::Struct(qpath, ..),
159                             ..
160                         })) => {
161                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
162                                 && qpath_ty.hir_id == ty.hir_id
163                             {
164                                 Some(path.span)
165                             } else {
166                                 None
167                             }
168                         }
169                         Some(Node::Expr(Expr {
170                             kind: ExprKind::Path(qpath),
171                             ..
172                         })) => {
173                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
174                                 && qpath_ty.hir_id == ty.hir_id
175                             {
176                                 Some(path.span)
177                             } else {
178                                 None
179                             }
180                         }
181                         // Can't unify these two branches because qpath below is `&&` and above is `&`
182                         // and `A | B` paths don't play well together with adjustments, apparently.
183                         Some(Node::Expr(Expr {
184                             kind: ExprKind::Struct(qpath, ..),
185                             ..
186                         })) => {
187                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
188                                 && qpath_ty.hir_id == ty.hir_id
189                             {
190                                 Some(path.span)
191                             } else {
192                                 None
193                             }
194                         }
195                         _ => None
196                     };
197 
198                     match span {
199                         Some(span) => {
200                             cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
201                                 suggestion: span,
202                             });
203                         },
204                         None => cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
205                     }
206                 } else if !ty.span.from_expansion() && path.segments.len() > 1 && let Some(ty) = is_ty_or_ty_ctxt(cx, &path) {
207                     cx.emit_spanned_lint(USAGE_OF_QUALIFIED_TY, path.span, TyQualified {
208                         ty,
209                         suggestion: path.span,
210                     });
211                 }
212             }
213             _ => {}
214         }
215     }
216 }
217 
lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool218 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
219     if let Some(did) = res.opt_def_id() {
220         cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
221     } else {
222         false
223     }
224 }
225 
is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String>226 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
227     match &path.res {
228         Res::Def(_, def_id) => {
229             if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
230                 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
231             }
232         }
233         // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
234         Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
235             if let ty::Adt(adt, substs) = cx.tcx.type_of(did).subst_identity().kind() {
236                 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
237                 {
238                     // NOTE: This path is currently unreachable as `Ty<'tcx>` is
239                     // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
240                     // is not actually allowed.
241                     //
242                     // I(@lcnr) still kept this branch in so we don't miss this
243                     // if we ever change it in the future.
244                     return Some(format!("{}<{}>", name, substs[0]));
245                 }
246             }
247         }
248         _ => (),
249     }
250 
251     None
252 }
253 
gen_args(segment: &PathSegment<'_>) -> String254 fn gen_args(segment: &PathSegment<'_>) -> String {
255     if let Some(args) = &segment.args {
256         let lifetimes = args
257             .args
258             .iter()
259             .filter_map(|arg| {
260                 if let GenericArg::Lifetime(lt) = arg { Some(lt.ident.to_string()) } else { None }
261             })
262             .collect::<Vec<_>>();
263 
264         if !lifetimes.is_empty() {
265             return format!("<{}>", lifetimes.join(", "));
266         }
267     }
268 
269     String::new()
270 }
271 
272 declare_tool_lint! {
273     /// The `lint_pass_impl_without_macro` detects manual implementations of a lint
274     /// pass, without using [`declare_lint_pass`] or [`impl_lint_pass`].
275     pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
276     Allow,
277     "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
278 }
279 
280 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
281 
282 impl EarlyLintPass for LintPassImpl {
check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item)283     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
284         if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
285             if let Some(last) = lint_pass.path.segments.last() {
286                 if last.ident.name == sym::LintPass {
287                     let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
288                     let call_site = expn_data.call_site;
289                     if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
290                         && call_site.ctxt().outer_expn_data().kind
291                             != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
292                     {
293                         cx.emit_spanned_lint(
294                             LINT_PASS_IMPL_WITHOUT_MACRO,
295                             lint_pass.path.span,
296                             LintPassByHand,
297                         );
298                     }
299                 }
300             }
301         }
302     }
303 }
304 
305 declare_tool_lint! {
306     /// The `existing_doc_keyword` lint detects use `#[doc()]` keywords
307     /// that don't exist, e.g. `#[doc(keyword = "..")]`.
308     pub rustc::EXISTING_DOC_KEYWORD,
309     Allow,
310     "Check that documented keywords in std and core actually exist",
311     report_in_external_macro: true
312 }
313 
314 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
315 
is_doc_keyword(s: Symbol) -> bool316 fn is_doc_keyword(s: Symbol) -> bool {
317     s <= kw::Union
318 }
319 
320 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>)321     fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
322         for attr in cx.tcx.hir().attrs(item.hir_id()) {
323             if !attr.has_name(sym::doc) {
324                 continue;
325             }
326             if let Some(list) = attr.meta_item_list() {
327                 for nested in list {
328                     if nested.has_name(sym::keyword) {
329                         let keyword = nested
330                             .value_str()
331                             .expect("#[doc(keyword = \"...\")] expected a value!");
332                         if is_doc_keyword(keyword) {
333                             return;
334                         }
335                         cx.emit_spanned_lint(
336                             EXISTING_DOC_KEYWORD,
337                             attr.span,
338                             NonExistentDocKeyword { keyword },
339                         );
340                     }
341                 }
342             }
343         }
344     }
345 }
346 
347 declare_tool_lint! {
348     /// The `untranslatable_diagnostic` lint detects diagnostics created
349     /// without using translatable Fluent strings.
350     ///
351     /// More details on translatable diagnostics can be found [here](https://rustc-dev-guide.rust-lang.org/diagnostics/translation.html).
352     pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
353     Allow,
354     "prevent creation of diagnostics which cannot be translated",
355     report_in_external_macro: true
356 }
357 
358 declare_tool_lint! {
359     /// The `diagnostic_outside_of_impl` lint detects diagnostics created manually,
360     /// and inside an `IntoDiagnostic`/`AddToDiagnostic` implementation,
361     /// or a `#[derive(Diagnostic)]`/`#[derive(Subdiagnostic)]` expansion.
362     ///
363     /// More details on diagnostics implementations can be found [here](https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html).
364     pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
365     Allow,
366     "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
367     report_in_external_macro: true
368 }
369 
370 declare_tool_lint! {
371     /// The `untranslatable_diagnostic_trivial` lint detects diagnostics created using only static strings.
372     pub rustc::UNTRANSLATABLE_DIAGNOSTIC_TRIVIAL,
373     Deny,
374     "prevent creation of diagnostics which cannot be translated, which use only static strings",
375     report_in_external_macro: true
376 }
377 
378 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL, UNTRANSLATABLE_DIAGNOSTIC_TRIVIAL ]);
379 
380 impl LateLintPass<'_> for Diagnostics {
check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>)381     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
382         let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
383         debug!(?span, ?def_id, ?substs);
384         let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
385             .ok()
386             .flatten()
387             .is_some_and(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics));
388         if !has_attr {
389             return;
390         }
391 
392         let mut found_parent_with_attr = false;
393         let mut found_impl = false;
394         for (hir_id, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
395             if let Some(owner_did) = hir_id.as_owner() {
396                 found_parent_with_attr = found_parent_with_attr
397                     || cx.tcx.has_attr(owner_did, sym::rustc_lint_diagnostics);
398             }
399 
400             debug!(?parent);
401             if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
402                 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
403                 let Some(def_id) = of_trait.trait_def_id() &&
404                 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
405                 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
406             {
407                 found_impl = true;
408                 break;
409             }
410         }
411         debug!(?found_impl);
412         if !found_parent_with_attr && !found_impl {
413             cx.emit_spanned_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, DiagOutOfImpl);
414         }
415 
416         let mut found_diagnostic_message = false;
417         for ty in substs.types() {
418             debug!(?ty);
419             if let Some(adt_def) = ty.ty_adt_def() &&
420                 let Some(name) =  cx.tcx.get_diagnostic_name(adt_def.did()) &&
421                 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
422             {
423                 found_diagnostic_message = true;
424                 break;
425             }
426         }
427         debug!(?found_diagnostic_message);
428         if !found_parent_with_attr && !found_diagnostic_message {
429             cx.emit_spanned_lint(UNTRANSLATABLE_DIAGNOSTIC, span, UntranslatableDiag);
430         }
431     }
432 }
433 
434 impl EarlyLintPass for Diagnostics {
435     #[allow(unused_must_use)]
check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt)436     fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
437         // Looking for a straight chain of method calls from 'struct_span_err' to 'emit'.
438         let ast::StmtKind::Semi(expr) = &stmt.kind else {
439             return;
440         };
441         let ast::ExprKind::MethodCall(meth) = &expr.kind else {
442             return;
443         };
444         if meth.seg.ident.name != sym::emit || !meth.args.is_empty() {
445             return;
446         }
447         let mut segments = vec![];
448         let mut cur = &meth.receiver;
449         let fake = &[].into();
450         loop {
451             match &cur.kind {
452                 ast::ExprKind::Call(func, args) => {
453                     if let ast::ExprKind::Path(_, path) = &func.kind {
454                         segments.push((path.segments.last().unwrap().ident.name, args))
455                     }
456                     break;
457                 }
458                 ast::ExprKind::MethodCall(method) => {
459                     segments.push((method.seg.ident.name, &method.args));
460                     cur = &method.receiver;
461                 }
462                 ast::ExprKind::MacCall(mac) => {
463                     segments.push((mac.path.segments.last().unwrap().ident.name, fake));
464                     break;
465                 }
466                 _ => {
467                     break;
468                 }
469             }
470         }
471         segments.reverse();
472         if segments.is_empty() {
473             return;
474         }
475         if segments[0].0.as_str() != "struct_span_err" {
476             return;
477         }
478         if !segments.iter().all(|(name, args)| {
479             let arg = match name.as_str() {
480                 "struct_span_err" | "span_note" | "span_label" | "span_help" if args.len() == 2 => {
481                     &args[1]
482                 }
483                 "note" | "help" if args.len() == 1 => &args[0],
484                 _ => {
485                     return false;
486                 }
487             };
488             if let ast::ExprKind::Lit(lit) = arg.kind
489                 && let ast::token::LitKind::Str = lit.kind {
490                     true
491             } else {
492                 false
493             }
494         }) {
495             return;
496         }
497         cx.emit_spanned_lint(
498             UNTRANSLATABLE_DIAGNOSTIC_TRIVIAL,
499             stmt.span,
500             UntranslatableDiagnosticTrivial,
501         );
502     }
503 }
504 
505 declare_tool_lint! {
506     /// The `bad_opt_access` lint detects accessing options by field instead of
507     /// the wrapper function.
508     pub rustc::BAD_OPT_ACCESS,
509     Deny,
510     "prevent using options by field access when there is a wrapper function",
511     report_in_external_macro: true
512 }
513 
514 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
515 
516 impl LateLintPass<'_> for BadOptAccess {
check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>)517     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
518         let ExprKind::Field(base, target) = expr.kind else { return };
519         let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
520         // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
521         // avoided.
522         if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
523             return;
524         }
525 
526         for field in adt_def.all_fields() {
527             if field.name == target.name &&
528                 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
529                 let Some(items) = attr.meta_item_list()  &&
530                 let Some(item) = items.first()  &&
531                 let Some(lit) = item.lit()  &&
532                 let ast::LitKind::Str(val, _) = lit.kind
533             {
534                 cx.emit_spanned_lint(BAD_OPT_ACCESS, expr.span, BadOptAccessDiag {
535                     msg: val.as_str(),
536                 });
537             }
538         }
539     }
540 }
541