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};
18 pub rustc::DEFAULT_HASH_TYPES,
20 "forbid HashMap and HashSet and suggest the FxHash* variants",
21 report_in_external_macro: true
24 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
26 impl LateLintPass<'_> for DefaultHashTypes {
27 fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
28 let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
29 if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
30 // don't lint imports, only actual usages
33 let replace = match cx.tcx.get_diagnostic_name(def_id) {
34 Some(sym::HashMap) => "FxHashMap",
35 Some(sym::HashSet) => "FxHashSet",
38 cx.struct_span_lint(DEFAULT_HASH_TYPES, path.span, |lint| {
39 lint.build(fluent::lint::default_hash_types)
40 .set_arg("preferred", replace)
41 .set_arg("used", cx.tcx.item_name(def_id))
42 .note(fluent::lint::note)
48 /// Helper function for lints that check for expressions with calls and use typeck results to
49 /// get the `DefId` and `SubstsRef` of the function.
50 fn typeck_results_of_method_fn<'tcx>(
51 cx: &LateContext<'tcx>,
53 ) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)> {
55 ExprKind::MethodCall(segment, _, _)
56 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
58 Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
61 match cx.typeck_results().node_type(expr.hir_id).kind() {
62 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
70 pub rustc::POTENTIAL_QUERY_INSTABILITY,
72 "require explicit opt-in when using potentially unstable methods or functions",
73 report_in_external_macro: true
76 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
78 impl LateLintPass<'_> for QueryStability {
79 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
80 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
81 if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) {
82 let def_id = instance.def_id();
83 if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) {
84 cx.struct_span_lint(POTENTIAL_QUERY_INSTABILITY, span, |lint| {
85 lint.build(fluent::lint::query_instability)
86 .set_arg("query", cx.tcx.item_name(def_id))
87 .note(fluent::lint::note)
96 pub rustc::USAGE_OF_TY_TYKIND,
98 "usage of `ty::TyKind` outside of the `ty::sty` module",
99 report_in_external_macro: true
103 pub rustc::USAGE_OF_QUALIFIED_TY,
105 "using `ty::{Ty,TyCtxt}` instead of importing it",
106 report_in_external_macro: true
109 declare_lint_pass!(TyTyKind => [
111 USAGE_OF_QUALIFIED_TY,
114 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
117 cx: &LateContext<'tcx>,
118 path: &'tcx rustc_hir::Path<'tcx>,
121 if let Some(segment) = path.segments.iter().nth_back(1)
122 && let Some(res) = &segment.res
123 && lint_ty_kind_usage(cx, res)
125 let span = path.span.with_hi(
126 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
128 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
129 lint.build(fluent::lint::tykind_kind)
132 fluent::lint::suggestion,
134 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 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
146 let hir = cx.tcx.hir();
147 match hir.find(hir.get_parent_node(ty.hir_id)) {
151 | PatKind::TupleStruct(qpath, ..)
152 | PatKind::Struct(qpath, ..),
155 if let QPath::TypeRelative(qpath_ty, ..) = qpath
156 && qpath_ty.hir_id == ty.hir_id
158 lint.build(fluent::lint::tykind_kind)
161 fluent::lint::suggestion,
163 Applicability::MaybeIncorrect, // ty maybe needs an import
169 Some(Node::Expr(Expr {
170 kind: ExprKind::Path(qpath),
173 if let QPath::TypeRelative(qpath_ty, ..) = qpath
174 && qpath_ty.hir_id == ty.hir_id
176 lint.build(fluent::lint::tykind_kind)
179 fluent::lint::suggestion,
181 Applicability::MaybeIncorrect, // ty maybe needs an import
187 // Can't unify these two branches because qpath below is `&&` and above is `&`
188 // and `A | B` paths don't play well together with adjustments, apparently.
189 Some(Node::Expr(Expr {
190 kind: ExprKind::Struct(qpath, ..),
193 if let QPath::TypeRelative(qpath_ty, ..) = qpath
194 && qpath_ty.hir_id == ty.hir_id
196 lint.build(fluent::lint::tykind_kind)
199 fluent::lint::suggestion,
201 Applicability::MaybeIncorrect, // ty maybe needs an import
209 lint.build(fluent::lint::tykind).help(fluent::lint::help).emit();
211 } else if !ty.span.from_expansion() && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
212 if path.segments.len() > 1 {
213 cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
214 lint.build(fluent::lint::ty_qualified)
215 .set_arg("ty", t.clone())
218 fluent::lint::suggestion,
220 // The import probably needs to be changed
221 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::SelfTy { trait_: None, alias_to: Some((did, _)) } => {
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 {
276 Some(lt.name.ident().to_string())
281 .collect::<Vec<_>>();
283 if !lifetimes.is_empty() {
284 return format!("<{}>", lifetimes.join(", "));
292 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
294 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
297 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
299 impl EarlyLintPass for LintPassImpl {
300 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
301 if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
302 if let Some(last) = lint_pass.path.segments.last() {
303 if last.ident.name == sym::LintPass {
304 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
305 let call_site = expn_data.call_site;
306 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
307 && call_site.ctxt().outer_expn_data().kind
308 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
311 LINT_PASS_IMPL_WITHOUT_MACRO,
314 lint.build(fluent::lint::lintpass_by_hand)
315 .help(fluent::lint::help)
327 pub rustc::EXISTING_DOC_KEYWORD,
329 "Check that documented keywords in std and core actually exist",
330 report_in_external_macro: true
333 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
335 fn is_doc_keyword(s: Symbol) -> bool {
339 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
340 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
341 for attr in cx.tcx.hir().attrs(item.hir_id()) {
342 if !attr.has_name(sym::doc) {
345 if let Some(list) = attr.meta_item_list() {
347 if nested.has_name(sym::keyword) {
350 .expect("#[doc(keyword = \"...\")] expected a value!");
351 if is_doc_keyword(v) {
354 cx.struct_span_lint(EXISTING_DOC_KEYWORD, attr.span, |lint| {
355 lint.build(fluent::lint::non_existant_doc_keyword)
356 .set_arg("keyword", v)
357 .help(fluent::lint::help)
368 pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
370 "prevent creation of diagnostics which cannot be translated",
371 report_in_external_macro: true
375 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
377 "prevent creation of diagnostics outside of `SessionDiagnostic`/`AddSubdiagnostic` impls",
378 report_in_external_macro: true
381 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
383 impl LateLintPass<'_> for Diagnostics {
384 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
385 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
386 debug!(?span, ?def_id, ?substs);
387 let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
389 .and_then(|inst| inst)
390 .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
396 let mut found_impl = false;
397 for (_, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
399 if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
400 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
401 let Some(def_id) = of_trait.trait_def_id() &&
402 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
403 matches!(name, sym::SessionDiagnostic | sym::AddSubdiagnostic | sym::DecorateLint)
411 cx.struct_span_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, |lint| {
412 lint.build(fluent::lint::diag_out_of_impl).emit();
416 let mut found_diagnostic_message = false;
417 for ty in substs.types() {
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)
423 found_diagnostic_message = true;
427 debug!(?found_diagnostic_message);
428 if !found_diagnostic_message {
429 cx.struct_span_lint(UNTRANSLATABLE_DIAGNOSTIC, span, |lint| {
430 lint.build(fluent::lint::untranslatable_diag).emit();
437 pub rustc::BAD_OPT_ACCESS,
439 "prevent using options by field access when there is a wrapper function",
440 report_in_external_macro: true
443 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
445 impl LateLintPass<'_> for BadOptAccess {
446 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
447 let ExprKind::Field(base, target) = expr.kind else { return };
448 let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
449 // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
451 if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
455 for field in adt_def.all_fields() {
456 if field.name == target.name &&
457 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
458 let Some(items) = attr.meta_item_list() &&
459 let Some(item) = items.first() &&
460 let Some(literal) = item.literal() &&
461 let ast::LitKind::Str(val, _) = literal.kind
463 cx.struct_span_lint(BAD_OPT_ACCESS, expr.span, |lint| {
464 lint.build(val.as_str()).emit(); }