1 //! Some lints that are only useful in the compiler or crates that use compiler internals, such as
5 BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand, NonExistantDocKeyword,
6 QueryInstability, TyQualified, TykindDiag, TykindKind, UntranslatableDiag,
8 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
10 use rustc_hir::def::Res;
11 use rustc_hir::{def_id::DefId, Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath};
12 use rustc_hir::{HirId, Impl, Item, ItemKind, Node, Pat, Ty, TyKind};
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::hygiene::{ExpnKind, MacroKind};
16 use rustc_span::symbol::{kw, sym, Symbol};
20 pub rustc::DEFAULT_HASH_TYPES,
22 "forbid HashMap and HashSet and suggest the FxHash* variants",
23 report_in_external_macro: true
26 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
28 impl LateLintPass<'_> for DefaultHashTypes {
29 fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
30 let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
31 if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
32 // don't lint imports, only actual usages
35 let preferred = match cx.tcx.get_diagnostic_name(def_id) {
36 Some(sym::HashMap) => "FxHashMap",
37 Some(sym::HashSet) => "FxHashSet",
43 DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) },
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) {
85 POTENTIAL_QUERY_INSTABILITY,
87 QueryInstability { query: cx.tcx.item_name(def_id) },
95 pub rustc::USAGE_OF_TY_TYKIND,
97 "usage of `ty::TyKind` outside of the `ty::sty` module",
98 report_in_external_macro: true
102 pub rustc::USAGE_OF_QUALIFIED_TY,
104 "using `ty::{Ty,TyCtxt}` instead of importing it",
105 report_in_external_macro: true
108 declare_lint_pass!(TyTyKind => [
110 USAGE_OF_QUALIFIED_TY,
113 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
116 cx: &LateContext<'tcx>,
117 path: &rustc_hir::Path<'tcx>,
120 if let Some(segment) = path.segments.iter().nth_back(1)
121 && lint_ty_kind_usage(cx, &segment.res)
123 let span = path.span.with_hi(
124 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
126 cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
132 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
134 TyKind::Path(QPath::Resolved(_, path)) => {
135 if lint_ty_kind_usage(cx, &path.res) {
136 let hir = cx.tcx.hir();
137 let span = match hir.find_parent(ty.hir_id) {
141 | PatKind::TupleStruct(qpath, ..)
142 | PatKind::Struct(qpath, ..),
145 if let QPath::TypeRelative(qpath_ty, ..) = qpath
146 && qpath_ty.hir_id == ty.hir_id
153 Some(Node::Expr(Expr {
154 kind: ExprKind::Path(qpath),
157 if let QPath::TypeRelative(qpath_ty, ..) = qpath
158 && qpath_ty.hir_id == ty.hir_id
165 // Can't unify these two branches because qpath below is `&&` and above is `&`
166 // and `A | B` paths don't play well together with adjustments, apparently.
167 Some(Node::Expr(Expr {
168 kind: ExprKind::Struct(qpath, ..),
171 if let QPath::TypeRelative(qpath_ty, ..) = qpath
172 && qpath_ty.hir_id == ty.hir_id
184 cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
188 None => cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
190 } else if !ty.span.from_expansion() && path.segments.len() > 1 && let Some(ty) = is_ty_or_ty_ctxt(cx, &path) {
191 cx.emit_spanned_lint(USAGE_OF_QUALIFIED_TY, path.span, TyQualified {
193 suggestion: path.span,
202 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
203 if let Some(did) = res.opt_def_id() {
204 cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
210 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
212 Res::Def(_, def_id) => {
213 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
214 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
217 // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
218 Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
219 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
220 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
222 // NOTE: This path is currently unreachable as `Ty<'tcx>` is
223 // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
224 // is not actually allowed.
226 // I(@lcnr) still kept this branch in so we don't miss this
227 // if we ever change it in the future.
228 return Some(format!("{}<{}>", name, substs[0]));
238 fn gen_args(segment: &PathSegment<'_>) -> String {
239 if let Some(args) = &segment.args {
244 if let GenericArg::Lifetime(lt) = arg { Some(lt.ident.to_string()) } else { None }
246 .collect::<Vec<_>>();
248 if !lifetimes.is_empty() {
249 return format!("<{}>", lifetimes.join(", "));
257 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
259 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
262 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
264 impl EarlyLintPass for LintPassImpl {
265 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
266 if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
267 if let Some(last) = lint_pass.path.segments.last() {
268 if last.ident.name == sym::LintPass {
269 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
270 let call_site = expn_data.call_site;
271 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
272 && call_site.ctxt().outer_expn_data().kind
273 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
275 cx.emit_spanned_lint(
276 LINT_PASS_IMPL_WITHOUT_MACRO,
288 pub rustc::EXISTING_DOC_KEYWORD,
290 "Check that documented keywords in std and core actually exist",
291 report_in_external_macro: true
294 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
296 fn is_doc_keyword(s: Symbol) -> bool {
300 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
301 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
302 for attr in cx.tcx.hir().attrs(item.hir_id()) {
303 if !attr.has_name(sym::doc) {
306 if let Some(list) = attr.meta_item_list() {
308 if nested.has_name(sym::keyword) {
311 .expect("#[doc(keyword = \"...\")] expected a value!");
312 if is_doc_keyword(keyword) {
315 cx.emit_spanned_lint(
316 EXISTING_DOC_KEYWORD,
318 NonExistantDocKeyword { keyword },
328 pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
330 "prevent creation of diagnostics which cannot be translated",
331 report_in_external_macro: true
335 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
337 "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
338 report_in_external_macro: true
341 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
343 impl LateLintPass<'_> for Diagnostics {
344 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
345 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
346 debug!(?span, ?def_id, ?substs);
347 let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
349 .and_then(|inst| inst)
350 .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
356 let mut found_parent_with_attr = false;
357 let mut found_impl = false;
358 for (hir_id, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
359 if let Some(owner_did) = hir_id.as_owner() {
360 found_parent_with_attr = found_parent_with_attr
361 || cx.tcx.has_attr(owner_did.to_def_id(), sym::rustc_lint_diagnostics);
365 if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
366 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
367 let Some(def_id) = of_trait.trait_def_id() &&
368 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
369 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
376 if !found_parent_with_attr && !found_impl {
377 cx.emit_spanned_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, DiagOutOfImpl);
380 let mut found_diagnostic_message = false;
381 for ty in substs.types() {
383 if let Some(adt_def) = ty.ty_adt_def() &&
384 let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did()) &&
385 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
387 found_diagnostic_message = true;
391 debug!(?found_diagnostic_message);
392 if !found_parent_with_attr && !found_diagnostic_message {
393 cx.emit_spanned_lint(UNTRANSLATABLE_DIAGNOSTIC, span, UntranslatableDiag);
399 pub rustc::BAD_OPT_ACCESS,
401 "prevent using options by field access when there is a wrapper function",
402 report_in_external_macro: true
405 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
407 impl LateLintPass<'_> for BadOptAccess {
408 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
409 let ExprKind::Field(base, target) = expr.kind else { return };
410 let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
411 // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
413 if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
417 for field in adt_def.all_fields() {
418 if field.name == target.name &&
419 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
420 let Some(items) = attr.meta_item_list() &&
421 let Some(item) = items.first() &&
422 let Some(lit) = item.lit() &&
423 let ast::LitKind::Str(val, _) = lit.kind
425 cx.emit_spanned_lint(BAD_OPT_ACCESS, expr.span, BadOptAccessDiag {