1 //! Some lints that are only useful in the compiler or crates that use compiler internals, such as
4 #![deny(rustc::untranslatable_diagnostic)]
5 #![deny(rustc::diagnostic_outside_of_impl)]
7 BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand, NonExistantDocKeyword,
8 QueryInstability, TyQualified, TykindDiag, TykindKind, UntranslatableDiag,
10 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
12 use rustc_hir::def::Res;
13 use rustc_hir::{def_id::DefId, Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath};
14 use rustc_hir::{HirId, Impl, Item, ItemKind, Node, Pat, Ty, TyKind};
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_span::hygiene::{ExpnKind, MacroKind};
18 use rustc_span::symbol::{kw, sym, Symbol};
22 pub rustc::DEFAULT_HASH_TYPES,
24 "forbid HashMap and HashSet and suggest the FxHash* variants",
25 report_in_external_macro: true
28 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
30 impl LateLintPass<'_> for DefaultHashTypes {
31 fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
32 let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
33 if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
34 // don't lint imports, only actual usages
37 let preferred = match cx.tcx.get_diagnostic_name(def_id) {
38 Some(sym::HashMap) => "FxHashMap",
39 Some(sym::HashSet) => "FxHashSet",
45 DefaultHashTypesDiag { preferred, 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 QueryInstability { query: cx.tcx.item_name(def_id) },
97 pub rustc::USAGE_OF_TY_TYKIND,
99 "usage of `ty::TyKind` outside of the `ty::sty` module",
100 report_in_external_macro: true
104 pub rustc::USAGE_OF_QUALIFIED_TY,
106 "using `ty::{Ty,TyCtxt}` instead of importing it",
107 report_in_external_macro: true
110 declare_lint_pass!(TyTyKind => [
112 USAGE_OF_QUALIFIED_TY,
115 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
118 cx: &LateContext<'tcx>,
119 path: &rustc_hir::Path<'tcx>,
122 if let Some(segment) = path.segments.iter().nth_back(1)
123 && lint_ty_kind_usage(cx, &segment.res)
125 let span = path.span.with_hi(
126 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
128 cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
134 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
136 TyKind::Path(QPath::Resolved(_, path)) => {
137 if lint_ty_kind_usage(cx, &path.res) {
138 let hir = cx.tcx.hir();
139 let span = match hir.find_parent(ty.hir_id) {
143 | PatKind::TupleStruct(qpath, ..)
144 | PatKind::Struct(qpath, ..),
147 if let QPath::TypeRelative(qpath_ty, ..) = qpath
148 && qpath_ty.hir_id == ty.hir_id
155 Some(Node::Expr(Expr {
156 kind: ExprKind::Path(qpath),
159 if let QPath::TypeRelative(qpath_ty, ..) = qpath
160 && qpath_ty.hir_id == ty.hir_id
167 // Can't unify these two branches because qpath below is `&&` and above is `&`
168 // and `A | B` paths don't play well together with adjustments, apparently.
169 Some(Node::Expr(Expr {
170 kind: ExprKind::Struct(qpath, ..),
173 if let QPath::TypeRelative(qpath_ty, ..) = qpath
174 && qpath_ty.hir_id == ty.hir_id
186 cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
190 None => cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
192 } else if !ty.span.from_expansion() && path.segments.len() > 1 && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
193 cx.emit_spanned_lint(USAGE_OF_QUALIFIED_TY, path.span, TyQualified {
195 suggestion: path.span,
204 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
205 if let Some(did) = res.opt_def_id() {
206 cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
212 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
214 Res::Def(_, def_id) => {
215 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
216 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
219 // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
220 Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
221 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
222 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
224 // NOTE: This path is currently unreachable as `Ty<'tcx>` is
225 // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
226 // is not actually allowed.
228 // I(@lcnr) still kept this branch in so we don't miss this
229 // if we ever change it in the future.
230 return Some(format!("{}<{}>", name, substs[0]));
240 fn gen_args(segment: &PathSegment<'_>) -> String {
241 if let Some(args) = &segment.args {
246 if let GenericArg::Lifetime(lt) = arg { Some(lt.ident.to_string()) } else { None }
248 .collect::<Vec<_>>();
250 if !lifetimes.is_empty() {
251 return format!("<{}>", lifetimes.join(", "));
259 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
261 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
264 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
266 impl EarlyLintPass for LintPassImpl {
267 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
268 if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
269 if let Some(last) = lint_pass.path.segments.last() {
270 if last.ident.name == sym::LintPass {
271 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
272 let call_site = expn_data.call_site;
273 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
274 && call_site.ctxt().outer_expn_data().kind
275 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
277 cx.emit_spanned_lint(
278 LINT_PASS_IMPL_WITHOUT_MACRO,
290 pub rustc::EXISTING_DOC_KEYWORD,
292 "Check that documented keywords in std and core actually exist",
293 report_in_external_macro: true
296 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
298 fn is_doc_keyword(s: Symbol) -> bool {
302 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
303 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
304 for attr in cx.tcx.hir().attrs(item.hir_id()) {
305 if !attr.has_name(sym::doc) {
308 if let Some(list) = attr.meta_item_list() {
310 if nested.has_name(sym::keyword) {
313 .expect("#[doc(keyword = \"...\")] expected a value!");
314 if is_doc_keyword(keyword) {
317 cx.emit_spanned_lint(
318 EXISTING_DOC_KEYWORD,
320 NonExistantDocKeyword { keyword },
330 pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
332 "prevent creation of diagnostics which cannot be translated",
333 report_in_external_macro: true
337 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
339 "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
340 report_in_external_macro: true
343 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
345 impl LateLintPass<'_> for Diagnostics {
346 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
347 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
348 debug!(?span, ?def_id, ?substs);
349 let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
351 .and_then(|inst| inst)
352 .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
358 let mut found_parent_with_attr = false;
359 let mut found_impl = false;
360 for (hir_id, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
361 if let Some(owner_did) = hir_id.as_owner() {
362 found_parent_with_attr = found_parent_with_attr
363 || cx.tcx.has_attr(owner_did.to_def_id(), sym::rustc_lint_diagnostics);
367 if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
368 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
369 let Some(def_id) = of_trait.trait_def_id() &&
370 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
371 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
378 if !found_parent_with_attr && !found_impl {
379 cx.emit_spanned_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, DiagOutOfImpl);
382 let mut found_diagnostic_message = false;
383 for ty in substs.types() {
385 if let Some(adt_def) = ty.ty_adt_def() &&
386 let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did()) &&
387 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
389 found_diagnostic_message = true;
393 debug!(?found_diagnostic_message);
394 if !found_parent_with_attr && !found_diagnostic_message {
395 cx.emit_spanned_lint(UNTRANSLATABLE_DIAGNOSTIC, span, UntranslatableDiag);
401 pub rustc::BAD_OPT_ACCESS,
403 "prevent using options by field access when there is a wrapper function",
404 report_in_external_macro: true
407 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
409 impl LateLintPass<'_> for BadOptAccess {
410 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
411 let ExprKind::Field(base, target) = expr.kind else { return };
412 let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
413 // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
415 if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
419 for field in adt_def.all_fields() {
420 if field.name == target.name &&
421 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
422 let Some(items) = attr.meta_item_list() &&
423 let Some(item) = items.first() &&
424 let Some(lit) = item.lit() &&
425 let ast::LitKind::Str(val, _) = lit.kind
427 cx.emit_spanned_lint(BAD_OPT_ACCESS, expr.span, BadOptAccessDiag {