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::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| {
40 "prefer `{}` over `{}`, it has better performance",
42 cx.tcx.item_name(def_id)
45 .note(&format!("a `use rustc_data_structures::fx::{}` may be necessary", replace))
51 /// Helper function for lints that check for expressions with calls and use typeck results to
52 /// get the `DefId` and `SubstsRef` of the function.
53 fn typeck_results_of_method_fn<'tcx>(
54 cx: &LateContext<'tcx>,
56 ) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)> {
57 // FIXME(rustdoc): Lints which use this function use typecheck results which can cause
58 // `rustdoc` to error if there are resolution failures.
60 // As internal lints are currently always run if there are `unstable_options`, they are added
61 // to the lint store of rustdoc. Internal lints are also not used via the `lint_mod` query.
62 // Crate lints run outside of a query so rustdoc currently doesn't disable them.
64 // Instead of relying on this, either change crate lints to a query disabled by rustdoc, only
65 // run internal lints if the user is explicitly opting in or figure out a different way to
66 // avoid running lints for rustdoc.
67 if cx.tcx.sess.opts.actually_rustdoc {
72 ExprKind::MethodCall(segment, _, _)
73 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
75 Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
78 match cx.typeck_results().node_type(expr.hir_id).kind() {
79 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
87 pub rustc::POTENTIAL_QUERY_INSTABILITY,
89 "require explicit opt-in when using potentially unstable methods or functions",
90 report_in_external_macro: true
93 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
95 impl LateLintPass<'_> for QueryStability {
96 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
97 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
98 if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) {
99 let def_id = instance.def_id();
100 if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) {
101 cx.struct_span_lint(POTENTIAL_QUERY_INSTABILITY, span, |lint| {
103 "using `{}` can result in unstable query results",
104 cx.tcx.item_name(def_id)
107 .note("if you believe this case to be fine, allow this lint and add a comment explaining your rationale")
116 pub rustc::USAGE_OF_TY_TYKIND,
118 "usage of `ty::TyKind` outside of the `ty::sty` module",
119 report_in_external_macro: true
123 pub rustc::USAGE_OF_QUALIFIED_TY,
125 "using `ty::{Ty,TyCtxt}` instead of importing it",
126 report_in_external_macro: true
129 declare_lint_pass!(TyTyKind => [
131 USAGE_OF_QUALIFIED_TY,
134 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
137 cx: &LateContext<'tcx>,
138 path: &'tcx rustc_hir::Path<'tcx>,
141 if let Some(segment) = path.segments.iter().nth_back(1)
142 && let Some(res) = &segment.res
143 && lint_ty_kind_usage(cx, res)
145 let span = path.span.with_hi(
146 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
148 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
149 lint.build("usage of `ty::TyKind::<kind>`")
152 "try using `ty::<kind>` directly",
154 Applicability::MaybeIncorrect, // ty maybe needs an import
161 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
163 TyKind::Path(QPath::Resolved(_, path)) => {
164 if lint_ty_kind_usage(cx, &path.res) {
165 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
166 let hir = cx.tcx.hir();
167 match hir.find(hir.get_parent_node(ty.hir_id)) {
171 | PatKind::TupleStruct(qpath, ..)
172 | PatKind::Struct(qpath, ..),
175 if let QPath::TypeRelative(qpath_ty, ..) = qpath
176 && qpath_ty.hir_id == ty.hir_id
178 lint.build("usage of `ty::TyKind::<kind>`")
181 "try using `ty::<kind>` directly",
183 Applicability::MaybeIncorrect, // ty maybe needs an import
189 Some(Node::Expr(Expr {
190 kind: ExprKind::Path(qpath),
193 if let QPath::TypeRelative(qpath_ty, ..) = qpath
194 && qpath_ty.hir_id == ty.hir_id
196 lint.build("usage of `ty::TyKind::<kind>`")
199 "try using `ty::<kind>` directly",
201 Applicability::MaybeIncorrect, // ty maybe needs an import
207 // Can't unify these two branches because qpath below is `&&` and above is `&`
208 // and `A | B` paths don't play well together with adjustments, apparently.
209 Some(Node::Expr(Expr {
210 kind: ExprKind::Struct(qpath, ..),
213 if let QPath::TypeRelative(qpath_ty, ..) = qpath
214 && qpath_ty.hir_id == ty.hir_id
216 lint.build("usage of `ty::TyKind::<kind>`")
219 "try using `ty::<kind>` directly",
221 Applicability::MaybeIncorrect, // ty maybe needs an import
229 lint.build("usage of `ty::TyKind`").help("try using `Ty` instead").emit();
231 } else if !ty.span.from_expansion() && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
232 if path.segments.len() > 1 {
233 cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
234 lint.build(&format!("usage of qualified `ty::{}`", t))
237 "try importing it and using it unqualified",
239 // The import probably needs to be changed
240 Applicability::MaybeIncorrect,
252 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
253 if let Some(did) = res.opt_def_id() {
254 cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
260 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
262 Res::Def(_, def_id) => {
263 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
264 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
267 // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
268 Res::SelfTy { trait_: None, alias_to: Some((did, _)) } => {
269 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
270 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
272 // NOTE: This path is currently unreachable as `Ty<'tcx>` is
273 // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
274 // is not actually allowed.
276 // I(@lcnr) still kept this branch in so we don't miss this
277 // if we ever change it in the future.
278 return Some(format!("{}<{}>", name, substs[0]));
288 fn gen_args(segment: &PathSegment<'_>) -> String {
289 if let Some(args) = &segment.args {
294 if let GenericArg::Lifetime(lt) = arg {
295 Some(lt.name.ident().to_string())
300 .collect::<Vec<_>>();
302 if !lifetimes.is_empty() {
303 return format!("<{}>", lifetimes.join(", "));
311 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
313 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
316 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
318 impl EarlyLintPass for LintPassImpl {
319 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
320 if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
321 if let Some(last) = lint_pass.path.segments.last() {
322 if last.ident.name == sym::LintPass {
323 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
324 let call_site = expn_data.call_site;
325 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
326 && call_site.ctxt().outer_expn_data().kind
327 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
330 LINT_PASS_IMPL_WITHOUT_MACRO,
333 lint.build("implementing `LintPass` by hand")
334 .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
346 pub rustc::EXISTING_DOC_KEYWORD,
348 "Check that documented keywords in std and core actually exist",
349 report_in_external_macro: true
352 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
354 fn is_doc_keyword(s: Symbol) -> bool {
358 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
359 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
360 for attr in cx.tcx.hir().attrs(item.hir_id()) {
361 if !attr.has_name(sym::doc) {
364 if let Some(list) = attr.meta_item_list() {
366 if nested.has_name(sym::keyword) {
369 .expect("#[doc(keyword = \"...\")] expected a value!");
370 if is_doc_keyword(v) {
373 cx.struct_span_lint(EXISTING_DOC_KEYWORD, attr.span, |lint| {
375 "Found non-existing keyword `{}` used in \
376 `#[doc(keyword = \"...\")]`",
379 .help("only existing keywords are allowed in core/std")
390 pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
392 "prevent creation of diagnostics which cannot be translated",
393 report_in_external_macro: true
397 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
399 "prevent creation of diagnostics outside of `SessionDiagnostic`/`AddSubdiagnostic` impls",
400 report_in_external_macro: true
403 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
405 impl LateLintPass<'_> for Diagnostics {
406 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
407 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
408 debug!(?span, ?def_id, ?substs);
409 if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) &&
410 !cx.tcx.has_attr(instance.def_id(), sym::rustc_lint_diagnostics)
415 let mut found_impl = false;
416 for (_, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
418 if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
419 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
420 let Some(def_id) = of_trait.trait_def_id() &&
421 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
422 matches!(name, sym::SessionDiagnostic | sym::AddSubdiagnostic)
430 cx.struct_span_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, |lint| {
431 lint.build("diagnostics should only be created in `SessionDiagnostic`/`AddSubdiagnostic` impls")
436 let mut found_diagnostic_message = false;
437 for ty in substs.types() {
439 if let Some(adt_def) = ty.ty_adt_def() &&
440 let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did()) &&
441 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
443 found_diagnostic_message = true;
447 debug!(?found_diagnostic_message);
448 if !found_diagnostic_message {
449 cx.struct_span_lint(UNTRANSLATABLE_DIAGNOSTIC, span, |lint| {
450 lint.build("diagnostics should be created using translatable messages").emit();