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>)> {
54 // FIXME(rustdoc): Lints which use this function use typecheck results which can cause
55 // `rustdoc` to error if there are resolution failures.
57 // As internal lints are currently always run if there are `unstable_options`, they are added
58 // to the lint store of rustdoc. Internal lints are also not used via the `lint_mod` query.
59 // Crate lints run outside of a query so rustdoc currently doesn't disable them.
61 // Instead of relying on this, either change crate lints to a query disabled by rustdoc, only
62 // run internal lints if the user is explicitly opting in or figure out a different way to
63 // avoid running lints for rustdoc.
64 if cx.tcx.sess.opts.actually_rustdoc {
69 ExprKind::MethodCall(segment, _, _)
70 if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
72 Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
75 match cx.typeck_results().node_type(expr.hir_id).kind() {
76 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
84 pub rustc::POTENTIAL_QUERY_INSTABILITY,
86 "require explicit opt-in when using potentially unstable methods or functions",
87 report_in_external_macro: true
90 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
92 impl LateLintPass<'_> for QueryStability {
93 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
94 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
95 if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) {
96 let def_id = instance.def_id();
97 if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) {
98 cx.struct_span_lint(POTENTIAL_QUERY_INSTABILITY, span, |lint| {
99 lint.build(fluent::lint::query_instability)
100 .set_arg("query", cx.tcx.item_name(def_id))
101 .note(fluent::lint::note)
110 pub rustc::USAGE_OF_TY_TYKIND,
112 "usage of `ty::TyKind` outside of the `ty::sty` module",
113 report_in_external_macro: true
117 pub rustc::USAGE_OF_QUALIFIED_TY,
119 "using `ty::{Ty,TyCtxt}` instead of importing it",
120 report_in_external_macro: true
123 declare_lint_pass!(TyTyKind => [
125 USAGE_OF_QUALIFIED_TY,
128 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
131 cx: &LateContext<'tcx>,
132 path: &'tcx rustc_hir::Path<'tcx>,
135 if let Some(segment) = path.segments.iter().nth_back(1)
136 && let Some(res) = &segment.res
137 && lint_ty_kind_usage(cx, res)
139 let span = path.span.with_hi(
140 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
142 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
143 lint.build(fluent::lint::tykind_kind)
146 fluent::lint::suggestion,
148 Applicability::MaybeIncorrect, // ty maybe needs an import
155 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
157 TyKind::Path(QPath::Resolved(_, path)) => {
158 if lint_ty_kind_usage(cx, &path.res) {
159 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
160 let hir = cx.tcx.hir();
161 match hir.find(hir.get_parent_node(ty.hir_id)) {
165 | PatKind::TupleStruct(qpath, ..)
166 | PatKind::Struct(qpath, ..),
169 if let QPath::TypeRelative(qpath_ty, ..) = qpath
170 && qpath_ty.hir_id == ty.hir_id
172 lint.build(fluent::lint::tykind_kind)
175 fluent::lint::suggestion,
177 Applicability::MaybeIncorrect, // ty maybe needs an import
183 Some(Node::Expr(Expr {
184 kind: ExprKind::Path(qpath),
187 if let QPath::TypeRelative(qpath_ty, ..) = qpath
188 && qpath_ty.hir_id == ty.hir_id
190 lint.build(fluent::lint::tykind_kind)
193 fluent::lint::suggestion,
195 Applicability::MaybeIncorrect, // ty maybe needs an import
201 // Can't unify these two branches because qpath below is `&&` and above is `&`
202 // and `A | B` paths don't play well together with adjustments, apparently.
203 Some(Node::Expr(Expr {
204 kind: ExprKind::Struct(qpath, ..),
207 if let QPath::TypeRelative(qpath_ty, ..) = qpath
208 && qpath_ty.hir_id == ty.hir_id
210 lint.build(fluent::lint::tykind_kind)
213 fluent::lint::suggestion,
215 Applicability::MaybeIncorrect, // ty maybe needs an import
223 lint.build(fluent::lint::tykind).help(fluent::lint::help).emit();
225 } else if !ty.span.from_expansion() && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
226 if path.segments.len() > 1 {
227 cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
228 lint.build(fluent::lint::ty_qualified)
229 .set_arg("ty", t.clone())
232 fluent::lint::suggestion,
234 // The import probably needs to be changed
235 Applicability::MaybeIncorrect,
247 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
248 if let Some(did) = res.opt_def_id() {
249 cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
255 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
257 Res::Def(_, def_id) => {
258 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
259 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
262 // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
263 Res::SelfTy { trait_: None, alias_to: Some((did, _)) } => {
264 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
265 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
267 // NOTE: This path is currently unreachable as `Ty<'tcx>` is
268 // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
269 // is not actually allowed.
271 // I(@lcnr) still kept this branch in so we don't miss this
272 // if we ever change it in the future.
273 return Some(format!("{}<{}>", name, substs[0]));
283 fn gen_args(segment: &PathSegment<'_>) -> String {
284 if let Some(args) = &segment.args {
289 if let GenericArg::Lifetime(lt) = arg {
290 Some(lt.name.ident().to_string())
295 .collect::<Vec<_>>();
297 if !lifetimes.is_empty() {
298 return format!("<{}>", lifetimes.join(", "));
306 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
308 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
311 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
313 impl EarlyLintPass for LintPassImpl {
314 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
315 if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
316 if let Some(last) = lint_pass.path.segments.last() {
317 if last.ident.name == sym::LintPass {
318 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
319 let call_site = expn_data.call_site;
320 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
321 && call_site.ctxt().outer_expn_data().kind
322 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
325 LINT_PASS_IMPL_WITHOUT_MACRO,
328 lint.build(fluent::lint::lintpass_by_hand)
329 .help(fluent::lint::help)
341 pub rustc::EXISTING_DOC_KEYWORD,
343 "Check that documented keywords in std and core actually exist",
344 report_in_external_macro: true
347 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
349 fn is_doc_keyword(s: Symbol) -> bool {
353 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
354 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
355 for attr in cx.tcx.hir().attrs(item.hir_id()) {
356 if !attr.has_name(sym::doc) {
359 if let Some(list) = attr.meta_item_list() {
361 if nested.has_name(sym::keyword) {
364 .expect("#[doc(keyword = \"...\")] expected a value!");
365 if is_doc_keyword(v) {
368 cx.struct_span_lint(EXISTING_DOC_KEYWORD, attr.span, |lint| {
369 lint.build(fluent::lint::non_existant_doc_keyword)
370 .set_arg("keyword", v)
371 .help(fluent::lint::help)
382 pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
384 "prevent creation of diagnostics which cannot be translated",
385 report_in_external_macro: true
389 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
391 "prevent creation of diagnostics outside of `SessionDiagnostic`/`AddSubdiagnostic` impls",
392 report_in_external_macro: true
395 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
397 impl LateLintPass<'_> for Diagnostics {
398 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
399 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
400 debug!(?span, ?def_id, ?substs);
401 let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
403 .and_then(|inst| inst)
404 .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
410 let mut found_impl = false;
411 for (_, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
413 if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
414 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
415 let Some(def_id) = of_trait.trait_def_id() &&
416 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
417 matches!(name, sym::SessionDiagnostic | sym::AddSubdiagnostic)
425 cx.struct_span_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, |lint| {
426 lint.build(fluent::lint::diag_out_of_impl).emit();
430 let mut found_diagnostic_message = false;
431 for ty in substs.types() {
433 if let Some(adt_def) = ty.ty_adt_def() &&
434 let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did()) &&
435 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
437 found_diagnostic_message = true;
441 debug!(?found_diagnostic_message);
442 if !found_diagnostic_message {
443 cx.struct_span_lint(UNTRANSLATABLE_DIAGNOSTIC, span, |lint| {
444 lint.build(fluent::lint::untranslatable_diag).emit();