]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/internal.rs
Rollup merge of #98519 - TaKO8Ki:add-head-span-field-to-item-and-impl-item, r=cjgillot
[rust.git] / compiler / rustc_lint / src / internal.rs
1 //! Some lints that are only useful in the compiler or crates that use compiler internals, such as
2 //! Clippy.
3
4 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
5 use rustc_ast as ast;
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};
10 use rustc_middle::ty;
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};
14 use rustc_span::Span;
15 use tracing::debug;
16
17 declare_tool_lint! {
18     pub rustc::DEFAULT_HASH_TYPES,
19     Allow,
20     "forbid HashMap and HashSet and suggest the FxHash* variants",
21     report_in_external_macro: true
22 }
23
24 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
25
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
31             return;
32         }
33         let replace = match cx.tcx.get_diagnostic_name(def_id) {
34             Some(sym::HashMap) => "FxHashMap",
35             Some(sym::HashSet) => "FxHashSet",
36             _ => return,
37         };
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)
43                 .emit();
44         });
45     }
46 }
47
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>,
52     expr: &Expr<'_>,
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.
56     //
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.
60     //
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 {
65         return None;
66     }
67
68     match expr.kind {
69         ExprKind::MethodCall(segment, _, _)
70             if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
71         {
72             Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
73         },
74         _ => {
75             match cx.typeck_results().node_type(expr.hir_id).kind() {
76                 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
77                 _ => None,
78             }
79         }
80     }
81 }
82
83 declare_tool_lint! {
84     pub rustc::POTENTIAL_QUERY_INSTABILITY,
85     Allow,
86     "require explicit opt-in when using potentially unstable methods or functions",
87     report_in_external_macro: true
88 }
89
90 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
91
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)
102                         .emit();
103                 })
104             }
105         }
106     }
107 }
108
109 declare_tool_lint! {
110     pub rustc::USAGE_OF_TY_TYKIND,
111     Allow,
112     "usage of `ty::TyKind` outside of the `ty::sty` module",
113     report_in_external_macro: true
114 }
115
116 declare_tool_lint! {
117     pub rustc::USAGE_OF_QUALIFIED_TY,
118     Allow,
119     "using `ty::{Ty,TyCtxt}` instead of importing it",
120     report_in_external_macro: true
121 }
122
123 declare_lint_pass!(TyTyKind => [
124     USAGE_OF_TY_TYKIND,
125     USAGE_OF_QUALIFIED_TY,
126 ]);
127
128 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
129     fn check_path(
130         &mut self,
131         cx: &LateContext<'tcx>,
132         path: &'tcx rustc_hir::Path<'tcx>,
133         _: rustc_hir::HirId,
134     ) {
135         if let Some(segment) = path.segments.iter().nth_back(1)
136         && let Some(res) = &segment.res
137         && lint_ty_kind_usage(cx, res)
138         {
139             let span = path.span.with_hi(
140                 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
141             );
142             cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
143                 lint.build(fluent::lint::tykind_kind)
144                     .span_suggestion(
145                         span,
146                         fluent::lint::suggestion,
147                         "ty",
148                         Applicability::MaybeIncorrect, // ty maybe needs an import
149                     )
150                     .emit();
151             });
152         }
153     }
154
155     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
156         match &ty.kind {
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)) {
162                             Some(Node::Pat(Pat {
163                                 kind:
164                                     PatKind::Path(qpath)
165                                     | PatKind::TupleStruct(qpath, ..)
166                                     | PatKind::Struct(qpath, ..),
167                                 ..
168                             })) => {
169                                 if let QPath::TypeRelative(qpath_ty, ..) = qpath
170                                     && qpath_ty.hir_id == ty.hir_id
171                                 {
172                                     lint.build(fluent::lint::tykind_kind)
173                                         .span_suggestion(
174                                             path.span,
175                                             fluent::lint::suggestion,
176                                             "ty",
177                                             Applicability::MaybeIncorrect, // ty maybe needs an import
178                                         )
179                                         .emit();
180                                     return;
181                                 }
182                             }
183                             Some(Node::Expr(Expr {
184                                 kind: ExprKind::Path(qpath),
185                                 ..
186                             })) => {
187                                 if let QPath::TypeRelative(qpath_ty, ..) = qpath
188                                     && qpath_ty.hir_id == ty.hir_id
189                                 {
190                                     lint.build(fluent::lint::tykind_kind)
191                                         .span_suggestion(
192                                             path.span,
193                                             fluent::lint::suggestion,
194                                             "ty",
195                                             Applicability::MaybeIncorrect, // ty maybe needs an import
196                                         )
197                                         .emit();
198                                     return;
199                                 }
200                             }
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, ..),
205                                 ..
206                             })) => {
207                                 if let QPath::TypeRelative(qpath_ty, ..) = qpath
208                                     && qpath_ty.hir_id == ty.hir_id
209                                 {
210                                     lint.build(fluent::lint::tykind_kind)
211                                         .span_suggestion(
212                                             path.span,
213                                             fluent::lint::suggestion,
214                                             "ty",
215                                             Applicability::MaybeIncorrect, // ty maybe needs an import
216                                         )
217                                         .emit();
218                                     return;
219                                 }
220                             }
221                             _ => {}
222                         }
223                         lint.build(fluent::lint::tykind).help(fluent::lint::help).emit();
224                     })
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())
230                                 .span_suggestion(
231                                     path.span,
232                                     fluent::lint::suggestion,
233                                     t,
234                                     // The import probably needs to be changed
235                                     Applicability::MaybeIncorrect,
236                                 )
237                                 .emit();
238                         })
239                     }
240                 }
241             }
242             _ => {}
243         }
244     }
245 }
246
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)
250     } else {
251         false
252     }
253 }
254
255 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
256     match &path.res {
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())));
260             }
261         }
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())
266                 {
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.
270                     //
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]));
274                 }
275             }
276         }
277         _ => (),
278     }
279
280     None
281 }
282
283 fn gen_args(segment: &PathSegment<'_>) -> String {
284     if let Some(args) = &segment.args {
285         let lifetimes = args
286             .args
287             .iter()
288             .filter_map(|arg| {
289                 if let GenericArg::Lifetime(lt) = arg {
290                     Some(lt.name.ident().to_string())
291                 } else {
292                     None
293                 }
294             })
295             .collect::<Vec<_>>();
296
297         if !lifetimes.is_empty() {
298             return format!("<{}>", lifetimes.join(", "));
299         }
300     }
301
302     String::new()
303 }
304
305 declare_tool_lint! {
306     pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
307     Allow,
308     "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
309 }
310
311 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
312
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)
323                     {
324                         cx.struct_span_lint(
325                             LINT_PASS_IMPL_WITHOUT_MACRO,
326                             lint_pass.path.span,
327                             |lint| {
328                                 lint.build(fluent::lint::lintpass_by_hand)
329                                     .help(fluent::lint::help)
330                                     .emit();
331                             },
332                         )
333                     }
334                 }
335             }
336         }
337     }
338 }
339
340 declare_tool_lint! {
341     pub rustc::EXISTING_DOC_KEYWORD,
342     Allow,
343     "Check that documented keywords in std and core actually exist",
344     report_in_external_macro: true
345 }
346
347 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
348
349 fn is_doc_keyword(s: Symbol) -> bool {
350     s <= kw::Union
351 }
352
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) {
357                 continue;
358             }
359             if let Some(list) = attr.meta_item_list() {
360                 for nested in list {
361                     if nested.has_name(sym::keyword) {
362                         let v = nested
363                             .value_str()
364                             .expect("#[doc(keyword = \"...\")] expected a value!");
365                         if is_doc_keyword(v) {
366                             return;
367                         }
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)
372                                 .emit();
373                         });
374                     }
375                 }
376             }
377         }
378     }
379 }
380
381 declare_tool_lint! {
382     pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
383     Allow,
384     "prevent creation of diagnostics which cannot be translated",
385     report_in_external_macro: true
386 }
387
388 declare_tool_lint! {
389     pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
390     Allow,
391     "prevent creation of diagnostics outside of `SessionDiagnostic`/`AddSubdiagnostic` impls",
392     report_in_external_macro: true
393 }
394
395 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
396
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)
402             .ok()
403             .and_then(|inst| inst)
404             .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
405             .unwrap_or(false);
406         if !has_attr {
407             return;
408         }
409
410         let mut found_impl = false;
411         for (_, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
412             debug!(?parent);
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 | sym::DecorateLint)
418             {
419                 found_impl = true;
420                 break;
421             }
422         }
423         debug!(?found_impl);
424         if !found_impl {
425             cx.struct_span_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, |lint| {
426                 lint.build(fluent::lint::diag_out_of_impl).emit();
427             })
428         }
429
430         let mut found_diagnostic_message = false;
431         for ty in substs.types() {
432             debug!(?ty);
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)
436             {
437                 found_diagnostic_message = true;
438                 break;
439             }
440         }
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();
445             })
446         }
447     }
448 }