]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/internal.rs
Auto merge of #95884 - cjgillot:assoc-item, r=lcnr
[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     match expr.kind {
55         ExprKind::MethodCall(segment, _, _)
56             if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
57         {
58             Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
59         },
60         _ => {
61             match cx.typeck_results().node_type(expr.hir_id).kind() {
62                 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
63                 _ => None,
64             }
65         }
66     }
67 }
68
69 declare_tool_lint! {
70     pub rustc::POTENTIAL_QUERY_INSTABILITY,
71     Allow,
72     "require explicit opt-in when using potentially unstable methods or functions",
73     report_in_external_macro: true
74 }
75
76 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
77
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) {
84                 cx.struct_span_lint(POTENTIAL_QUERY_INSTABILITY, span, |lint| {
85                     lint.build(fluent::lint::query_instability)
86                         .set_arg("query", cx.tcx.item_name(def_id))
87                         .note(fluent::lint::note)
88                         .emit();
89                 })
90             }
91         }
92     }
93 }
94
95 declare_tool_lint! {
96     pub rustc::USAGE_OF_TY_TYKIND,
97     Allow,
98     "usage of `ty::TyKind` outside of the `ty::sty` module",
99     report_in_external_macro: true
100 }
101
102 declare_tool_lint! {
103     pub rustc::USAGE_OF_QUALIFIED_TY,
104     Allow,
105     "using `ty::{Ty,TyCtxt}` instead of importing it",
106     report_in_external_macro: true
107 }
108
109 declare_lint_pass!(TyTyKind => [
110     USAGE_OF_TY_TYKIND,
111     USAGE_OF_QUALIFIED_TY,
112 ]);
113
114 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
115     fn check_path(
116         &mut self,
117         cx: &LateContext<'tcx>,
118         path: &'tcx rustc_hir::Path<'tcx>,
119         _: rustc_hir::HirId,
120     ) {
121         if let Some(segment) = path.segments.iter().nth_back(1)
122         && let Some(res) = &segment.res
123         && lint_ty_kind_usage(cx, res)
124         {
125             let span = path.span.with_hi(
126                 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
127             );
128             cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
129                 lint.build(fluent::lint::tykind_kind)
130                     .span_suggestion(
131                         span,
132                         fluent::lint::suggestion,
133                         "ty",
134                         Applicability::MaybeIncorrect, // ty maybe needs an import
135                     )
136                     .emit();
137             });
138         }
139     }
140
141     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
142         match &ty.kind {
143             TyKind::Path(QPath::Resolved(_, path)) => {
144                 if lint_ty_kind_usage(cx, &path.res) {
145                     cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
146                         let hir = cx.tcx.hir();
147                         match hir.find(hir.get_parent_node(ty.hir_id)) {
148                             Some(Node::Pat(Pat {
149                                 kind:
150                                     PatKind::Path(qpath)
151                                     | PatKind::TupleStruct(qpath, ..)
152                                     | PatKind::Struct(qpath, ..),
153                                 ..
154                             })) => {
155                                 if let QPath::TypeRelative(qpath_ty, ..) = qpath
156                                     && qpath_ty.hir_id == ty.hir_id
157                                 {
158                                     lint.build(fluent::lint::tykind_kind)
159                                         .span_suggestion(
160                                             path.span,
161                                             fluent::lint::suggestion,
162                                             "ty",
163                                             Applicability::MaybeIncorrect, // ty maybe needs an import
164                                         )
165                                         .emit();
166                                     return;
167                                 }
168                             }
169                             Some(Node::Expr(Expr {
170                                 kind: ExprKind::Path(qpath),
171                                 ..
172                             })) => {
173                                 if let QPath::TypeRelative(qpath_ty, ..) = qpath
174                                     && qpath_ty.hir_id == ty.hir_id
175                                 {
176                                     lint.build(fluent::lint::tykind_kind)
177                                         .span_suggestion(
178                                             path.span,
179                                             fluent::lint::suggestion,
180                                             "ty",
181                                             Applicability::MaybeIncorrect, // ty maybe needs an import
182                                         )
183                                         .emit();
184                                     return;
185                                 }
186                             }
187                             // Can't unify these two branches because qpath below is `&&` and above is `&`
188                             // and `A | B` paths don't play well together with adjustments, apparently.
189                             Some(Node::Expr(Expr {
190                                 kind: ExprKind::Struct(qpath, ..),
191                                 ..
192                             })) => {
193                                 if let QPath::TypeRelative(qpath_ty, ..) = qpath
194                                     && qpath_ty.hir_id == ty.hir_id
195                                 {
196                                     lint.build(fluent::lint::tykind_kind)
197                                         .span_suggestion(
198                                             path.span,
199                                             fluent::lint::suggestion,
200                                             "ty",
201                                             Applicability::MaybeIncorrect, // ty maybe needs an import
202                                         )
203                                         .emit();
204                                     return;
205                                 }
206                             }
207                             _ => {}
208                         }
209                         lint.build(fluent::lint::tykind).help(fluent::lint::help).emit();
210                     })
211                 } else if !ty.span.from_expansion() && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
212                     if path.segments.len() > 1 {
213                         cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
214                             lint.build(fluent::lint::ty_qualified)
215                                 .set_arg("ty", t.clone())
216                                 .span_suggestion(
217                                     path.span,
218                                     fluent::lint::suggestion,
219                                     t,
220                                     // The import probably needs to be changed
221                                     Applicability::MaybeIncorrect,
222                                 )
223                                 .emit();
224                         })
225                     }
226                 }
227             }
228             _ => {}
229         }
230     }
231 }
232
233 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
234     if let Some(did) = res.opt_def_id() {
235         cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
236     } else {
237         false
238     }
239 }
240
241 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
242     match &path.res {
243         Res::Def(_, def_id) => {
244             if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
245                 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
246             }
247         }
248         // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
249         Res::SelfTy { trait_: None, alias_to: Some((did, _)) } => {
250             if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
251                 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
252                 {
253                     // NOTE: This path is currently unreachable as `Ty<'tcx>` is
254                     // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
255                     // is not actually allowed.
256                     //
257                     // I(@lcnr) still kept this branch in so we don't miss this
258                     // if we ever change it in the future.
259                     return Some(format!("{}<{}>", name, substs[0]));
260                 }
261             }
262         }
263         _ => (),
264     }
265
266     None
267 }
268
269 fn gen_args(segment: &PathSegment<'_>) -> String {
270     if let Some(args) = &segment.args {
271         let lifetimes = args
272             .args
273             .iter()
274             .filter_map(|arg| {
275                 if let GenericArg::Lifetime(lt) = arg {
276                     Some(lt.name.ident().to_string())
277                 } else {
278                     None
279                 }
280             })
281             .collect::<Vec<_>>();
282
283         if !lifetimes.is_empty() {
284             return format!("<{}>", lifetimes.join(", "));
285         }
286     }
287
288     String::new()
289 }
290
291 declare_tool_lint! {
292     pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
293     Allow,
294     "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
295 }
296
297 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
298
299 impl EarlyLintPass for LintPassImpl {
300     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
301         if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
302             if let Some(last) = lint_pass.path.segments.last() {
303                 if last.ident.name == sym::LintPass {
304                     let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
305                     let call_site = expn_data.call_site;
306                     if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
307                         && call_site.ctxt().outer_expn_data().kind
308                             != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
309                     {
310                         cx.struct_span_lint(
311                             LINT_PASS_IMPL_WITHOUT_MACRO,
312                             lint_pass.path.span,
313                             |lint| {
314                                 lint.build(fluent::lint::lintpass_by_hand)
315                                     .help(fluent::lint::help)
316                                     .emit();
317                             },
318                         )
319                     }
320                 }
321             }
322         }
323     }
324 }
325
326 declare_tool_lint! {
327     pub rustc::EXISTING_DOC_KEYWORD,
328     Allow,
329     "Check that documented keywords in std and core actually exist",
330     report_in_external_macro: true
331 }
332
333 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
334
335 fn is_doc_keyword(s: Symbol) -> bool {
336     s <= kw::Union
337 }
338
339 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
340     fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
341         for attr in cx.tcx.hir().attrs(item.hir_id()) {
342             if !attr.has_name(sym::doc) {
343                 continue;
344             }
345             if let Some(list) = attr.meta_item_list() {
346                 for nested in list {
347                     if nested.has_name(sym::keyword) {
348                         let v = nested
349                             .value_str()
350                             .expect("#[doc(keyword = \"...\")] expected a value!");
351                         if is_doc_keyword(v) {
352                             return;
353                         }
354                         cx.struct_span_lint(EXISTING_DOC_KEYWORD, attr.span, |lint| {
355                             lint.build(fluent::lint::non_existant_doc_keyword)
356                                 .set_arg("keyword", v)
357                                 .help(fluent::lint::help)
358                                 .emit();
359                         });
360                     }
361                 }
362             }
363         }
364     }
365 }
366
367 declare_tool_lint! {
368     pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
369     Allow,
370     "prevent creation of diagnostics which cannot be translated",
371     report_in_external_macro: true
372 }
373
374 declare_tool_lint! {
375     pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
376     Allow,
377     "prevent creation of diagnostics outside of `SessionDiagnostic`/`AddSubdiagnostic` impls",
378     report_in_external_macro: true
379 }
380
381 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
382
383 impl LateLintPass<'_> for Diagnostics {
384     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
385         let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
386         debug!(?span, ?def_id, ?substs);
387         let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
388             .ok()
389             .and_then(|inst| inst)
390             .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
391             .unwrap_or(false);
392         if !has_attr {
393             return;
394         }
395
396         let mut found_impl = false;
397         for (_, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
398             debug!(?parent);
399             if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
400                 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
401                 let Some(def_id) = of_trait.trait_def_id() &&
402                 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
403                 matches!(name, sym::SessionDiagnostic | sym::AddSubdiagnostic | sym::DecorateLint)
404             {
405                 found_impl = true;
406                 break;
407             }
408         }
409         debug!(?found_impl);
410         if !found_impl {
411             cx.struct_span_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, |lint| {
412                 lint.build(fluent::lint::diag_out_of_impl).emit();
413             })
414         }
415
416         let mut found_diagnostic_message = false;
417         for ty in substs.types() {
418             debug!(?ty);
419             if let Some(adt_def) = ty.ty_adt_def() &&
420                 let Some(name) =  cx.tcx.get_diagnostic_name(adt_def.did()) &&
421                 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
422             {
423                 found_diagnostic_message = true;
424                 break;
425             }
426         }
427         debug!(?found_diagnostic_message);
428         if !found_diagnostic_message {
429             cx.struct_span_lint(UNTRANSLATABLE_DIAGNOSTIC, span, |lint| {
430                 lint.build(fluent::lint::untranslatable_diag).emit();
431             })
432         }
433     }
434 }
435
436 declare_tool_lint! {
437     pub rustc::BAD_OPT_ACCESS,
438     Deny,
439     "prevent using options by field access when there is a wrapper function",
440     report_in_external_macro: true
441 }
442
443 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
444
445 impl LateLintPass<'_> for BadOptAccess {
446     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
447         let ExprKind::Field(base, target) = expr.kind else { return };
448         let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
449         // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
450         // avoided.
451         if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
452             return;
453         }
454
455         for field in adt_def.all_fields() {
456             if field.name == target.name &&
457                 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
458                 let Some(items) = attr.meta_item_list()  &&
459                 let Some(item) = items.first()  &&
460                 let Some(literal) = item.literal()  &&
461                 let ast::LitKind::Str(val, _) = literal.kind
462             {
463                 cx.struct_span_lint(BAD_OPT_ACCESS, expr.span, |lint| {
464                     lint.build(val.as_str()).emit(); }
465                 );
466             }
467         }
468     }
469 }