1 //! Some lints that are only useful in the compiler or crates that use compiler internals, such as
4 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
6 use rustc_errors::{fluent, Applicability};
7 use rustc_hir::def::Res;
8 use rustc_hir::{def_id::DefId, Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath};
9 use rustc_hir::{HirId, Impl, Item, ItemKind, Node, Pat, Ty, TyKind};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::hygiene::{ExpnKind, MacroKind};
13 use rustc_span::symbol::{kw, sym, Symbol};
17 pub rustc::DEFAULT_HASH_TYPES,
19 "forbid HashMap and HashSet and suggest the FxHash* variants",
20 report_in_external_macro: true
23 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
25 impl LateLintPass<'_> for DefaultHashTypes {
26 fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
27 let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
28 if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
29 // don't lint imports, only actual usages
32 let replace = match cx.tcx.get_diagnostic_name(def_id) {
33 Some(sym::HashMap) => "FxHashMap",
34 Some(sym::HashSet) => "FxHashSet",
40 fluent::lint_default_hash_types,
42 lint.set_arg("preferred", replace)
43 .set_arg("used", cx.tcx.item_name(def_id))
50 /// Helper function for lints that check for expressions with calls and use typeck results to
51 /// get the `DefId` and `SubstsRef` of the function.
52 fn typeck_results_of_method_fn<'tcx>(
53 cx: &LateContext<'tcx>,
55 ) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)> {
57 ExprKind::MethodCall(segment, ..)
58 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
60 Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
63 match cx.typeck_results().node_type(expr.hir_id).kind() {
64 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
72 pub rustc::POTENTIAL_QUERY_INSTABILITY,
74 "require explicit opt-in when using potentially unstable methods or functions",
75 report_in_external_macro: true
78 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
80 impl LateLintPass<'_> for QueryStability {
81 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
82 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
83 if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) {
84 let def_id = instance.def_id();
85 if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) {
87 POTENTIAL_QUERY_INSTABILITY,
89 fluent::lint_query_instability,
90 |lint| lint.set_arg("query", cx.tcx.item_name(def_id)).note(fluent::note),
98 pub rustc::USAGE_OF_TY_TYKIND,
100 "usage of `ty::TyKind` outside of the `ty::sty` module",
101 report_in_external_macro: true
105 pub rustc::USAGE_OF_QUALIFIED_TY,
107 "using `ty::{Ty,TyCtxt}` instead of importing it",
108 report_in_external_macro: true
111 declare_lint_pass!(TyTyKind => [
113 USAGE_OF_QUALIFIED_TY,
116 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
119 cx: &LateContext<'tcx>,
120 path: &'tcx rustc_hir::Path<'tcx>,
123 if let Some(segment) = path.segments.iter().nth_back(1)
124 && lint_ty_kind_usage(cx, &segment.res)
126 let span = path.span.with_hi(
127 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
129 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, fluent::lint_tykind_kind, |lint| {
135 Applicability::MaybeIncorrect, // ty maybe needs an import
141 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
143 TyKind::Path(QPath::Resolved(_, path)) => {
144 if lint_ty_kind_usage(cx, &path.res) {
145 let hir = cx.tcx.hir();
146 let span = match hir.find(hir.get_parent_node(ty.hir_id)) {
150 | PatKind::TupleStruct(qpath, ..)
151 | PatKind::Struct(qpath, ..),
154 if let QPath::TypeRelative(qpath_ty, ..) = qpath
155 && qpath_ty.hir_id == ty.hir_id
162 Some(Node::Expr(Expr {
163 kind: ExprKind::Path(qpath),
166 if let QPath::TypeRelative(qpath_ty, ..) = qpath
167 && qpath_ty.hir_id == ty.hir_id
174 // Can't unify these two branches because qpath below is `&&` and above is `&`
175 // and `A | B` paths don't play well together with adjustments, apparently.
176 Some(Node::Expr(Expr {
177 kind: ExprKind::Struct(qpath, ..),
180 if let QPath::TypeRelative(qpath_ty, ..) = qpath
181 && qpath_ty.hir_id == ty.hir_id
196 fluent::lint_tykind_kind,
197 |lint| lint.span_suggestion(
201 Applicability::MaybeIncorrect, // ty maybe needs an import
205 None => cx.struct_span_lint(
209 |lint| lint.help(fluent::help)
212 } else if !ty.span.from_expansion() && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
213 if path.segments.len() > 1 {
214 cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, fluent::lint_ty_qualified, |lint| {
216 .set_arg("ty", t.clone())
221 // The import probably needs to be changed
222 Applicability::MaybeIncorrect,
233 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
234 if let Some(did) = res.opt_def_id() {
235 cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
241 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
243 Res::Def(_, def_id) => {
244 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
245 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
248 // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
249 Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
250 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
251 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
253 // NOTE: This path is currently unreachable as `Ty<'tcx>` is
254 // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
255 // is not actually allowed.
257 // I(@lcnr) still kept this branch in so we don't miss this
258 // if we ever change it in the future.
259 return Some(format!("{}<{}>", name, substs[0]));
269 fn gen_args(segment: &PathSegment<'_>) -> String {
270 if let Some(args) = &segment.args {
275 if let GenericArg::Lifetime(lt) = arg { Some(lt.ident.to_string()) } else { None }
277 .collect::<Vec<_>>();
279 if !lifetimes.is_empty() {
280 return format!("<{}>", lifetimes.join(", "));
288 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
290 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
293 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
295 impl EarlyLintPass for LintPassImpl {
296 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
297 if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
298 if let Some(last) = lint_pass.path.segments.last() {
299 if last.ident.name == sym::LintPass {
300 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
301 let call_site = expn_data.call_site;
302 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
303 && call_site.ctxt().outer_expn_data().kind
304 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
307 LINT_PASS_IMPL_WITHOUT_MACRO,
309 fluent::lint_lintpass_by_hand,
310 |lint| lint.help(fluent::help),
320 pub rustc::EXISTING_DOC_KEYWORD,
322 "Check that documented keywords in std and core actually exist",
323 report_in_external_macro: true
326 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
328 fn is_doc_keyword(s: Symbol) -> bool {
332 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
333 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
334 for attr in cx.tcx.hir().attrs(item.hir_id()) {
335 if !attr.has_name(sym::doc) {
338 if let Some(list) = attr.meta_item_list() {
340 if nested.has_name(sym::keyword) {
343 .expect("#[doc(keyword = \"...\")] expected a value!");
344 if is_doc_keyword(v) {
348 EXISTING_DOC_KEYWORD,
350 fluent::lint_non_existant_doc_keyword,
351 |lint| lint.set_arg("keyword", v).help(fluent::help),
361 pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
363 "prevent creation of diagnostics which cannot be translated",
364 report_in_external_macro: true
368 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
370 "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
371 report_in_external_macro: true
374 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
376 impl LateLintPass<'_> for Diagnostics {
377 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
378 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
379 debug!(?span, ?def_id, ?substs);
380 let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
382 .and_then(|inst| inst)
383 .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
389 let mut found_parent_with_attr = false;
390 let mut found_impl = false;
391 for (hir_id, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
392 if let Some(owner_did) = hir_id.as_owner() {
393 found_parent_with_attr = found_parent_with_attr
394 || cx.tcx.has_attr(owner_did.to_def_id(), sym::rustc_lint_diagnostics);
398 if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
399 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
400 let Some(def_id) = of_trait.trait_def_id() &&
401 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
402 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
409 if !found_parent_with_attr && !found_impl {
411 DIAGNOSTIC_OUTSIDE_OF_IMPL,
413 fluent::lint_diag_out_of_impl,
418 let mut found_diagnostic_message = false;
419 for ty in substs.types() {
421 if let Some(adt_def) = ty.ty_adt_def() &&
422 let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did()) &&
423 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
425 found_diagnostic_message = true;
429 debug!(?found_diagnostic_message);
430 if !found_parent_with_attr && !found_diagnostic_message {
432 UNTRANSLATABLE_DIAGNOSTIC,
434 fluent::lint_untranslatable_diag,
442 pub rustc::BAD_OPT_ACCESS,
444 "prevent using options by field access when there is a wrapper function",
445 report_in_external_macro: true
448 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
450 impl LateLintPass<'_> for BadOptAccess {
451 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
452 let ExprKind::Field(base, target) = expr.kind else { return };
453 let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
454 // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
456 if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
460 for field in adt_def.all_fields() {
461 if field.name == target.name &&
462 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
463 let Some(items) = attr.meta_item_list() &&
464 let Some(item) = items.first() &&
465 let Some(lit) = item.lit() &&
466 let ast::LitKind::Str(val, _) = lit.kind
468 cx.struct_span_lint(BAD_OPT_ACCESS, expr.span, val.as_str(), |lint|