]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/internal.rs
Rollup merge of #104853 - jyn514:sysroot-typo, r=RalfJung
[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
16 declare_tool_lint! {
17     pub rustc::DEFAULT_HASH_TYPES,
18     Allow,
19     "forbid HashMap and HashSet and suggest the FxHash* variants",
20     report_in_external_macro: true
21 }
22
23 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
24
25 impl LateLintPass<'_> for DefaultHashTypes {
26     fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
27         let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
28         if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
29             // don't lint imports, only actual usages
30             return;
31         }
32         let replace = match cx.tcx.get_diagnostic_name(def_id) {
33             Some(sym::HashMap) => "FxHashMap",
34             Some(sym::HashSet) => "FxHashSet",
35             _ => return,
36         };
37         cx.struct_span_lint(
38             DEFAULT_HASH_TYPES,
39             path.span,
40             fluent::lint_default_hash_types,
41             |lint| {
42                 lint.set_arg("preferred", replace)
43                     .set_arg("used", cx.tcx.item_name(def_id))
44                     .note(fluent::note)
45             },
46         );
47     }
48 }
49
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>,
54     expr: &Expr<'_>,
55 ) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)> {
56     match expr.kind {
57         ExprKind::MethodCall(segment, ..)
58             if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) =>
59         {
60             Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)))
61         },
62         _ => {
63             match cx.typeck_results().node_type(expr.hir_id).kind() {
64                 &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)),
65                 _ => None,
66             }
67         }
68     }
69 }
70
71 declare_tool_lint! {
72     pub rustc::POTENTIAL_QUERY_INSTABILITY,
73     Allow,
74     "require explicit opt-in when using potentially unstable methods or functions",
75     report_in_external_macro: true
76 }
77
78 declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
79
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) {
86                 cx.struct_span_lint(
87                     POTENTIAL_QUERY_INSTABILITY,
88                     span,
89                     fluent::lint_query_instability,
90                     |lint| lint.set_arg("query", cx.tcx.item_name(def_id)).note(fluent::note),
91                 )
92             }
93         }
94     }
95 }
96
97 declare_tool_lint! {
98     pub rustc::USAGE_OF_TY_TYKIND,
99     Allow,
100     "usage of `ty::TyKind` outside of the `ty::sty` module",
101     report_in_external_macro: true
102 }
103
104 declare_tool_lint! {
105     pub rustc::USAGE_OF_QUALIFIED_TY,
106     Allow,
107     "using `ty::{Ty,TyCtxt}` instead of importing it",
108     report_in_external_macro: true
109 }
110
111 declare_lint_pass!(TyTyKind => [
112     USAGE_OF_TY_TYKIND,
113     USAGE_OF_QUALIFIED_TY,
114 ]);
115
116 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
117     fn check_path(
118         &mut self,
119         cx: &LateContext<'tcx>,
120         path: &'tcx rustc_hir::Path<'tcx>,
121         _: rustc_hir::HirId,
122     ) {
123         if let Some(segment) = path.segments.iter().nth_back(1)
124         && lint_ty_kind_usage(cx, &segment.res)
125         {
126             let span = path.span.with_hi(
127                 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
128             );
129             cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, fluent::lint_tykind_kind, |lint| {
130                 lint
131                     .span_suggestion(
132                         span,
133                         fluent::suggestion,
134                         "ty",
135                         Applicability::MaybeIncorrect, // ty maybe needs an import
136                     )
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                     let hir = cx.tcx.hir();
146                     let span = match hir.find(hir.get_parent_node(ty.hir_id)) {
147                         Some(Node::Pat(Pat {
148                             kind:
149                                 PatKind::Path(qpath)
150                                 | PatKind::TupleStruct(qpath, ..)
151                                 | PatKind::Struct(qpath, ..),
152                             ..
153                         })) => {
154                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
155                                 && qpath_ty.hir_id == ty.hir_id
156                             {
157                                 Some(path.span)
158                             } else {
159                                 None
160                             }
161                         }
162                         Some(Node::Expr(Expr {
163                             kind: ExprKind::Path(qpath),
164                             ..
165                         })) => {
166                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
167                                 && qpath_ty.hir_id == ty.hir_id
168                             {
169                                 Some(path.span)
170                             } else {
171                                 None
172                             }
173                         }
174                         // Can't unify these two branches because qpath below is `&&` and above is `&`
175                         // and `A | B` paths don't play well together with adjustments, apparently.
176                         Some(Node::Expr(Expr {
177                             kind: ExprKind::Struct(qpath, ..),
178                             ..
179                         })) => {
180                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
181                                 && qpath_ty.hir_id == ty.hir_id
182                             {
183                                 Some(path.span)
184                             } else {
185                                 None
186                             }
187                         }
188                         _ => None
189                     };
190
191                     match span {
192                         Some(span) => {
193                             cx.struct_span_lint(
194                                 USAGE_OF_TY_TYKIND,
195                                 path.span,
196                                 fluent::lint_tykind_kind,
197                                 |lint| lint.span_suggestion(
198                                     span,
199                                     fluent::suggestion,
200                                     "ty",
201                                     Applicability::MaybeIncorrect, // ty maybe needs an import
202                                 )
203                             )
204                         },
205                         None => cx.struct_span_lint(
206                             USAGE_OF_TY_TYKIND,
207                             path.span,
208                             fluent::lint_tykind,
209                             |lint| lint.help(fluent::help)
210                         )
211                     }
212                 } else if !ty.span.from_expansion() && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
213                     if path.segments.len() > 1 {
214                         cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, fluent::lint_ty_qualified, |lint| {
215                             lint
216                                 .set_arg("ty", t.clone())
217                                 .span_suggestion(
218                                     path.span,
219                                     fluent::suggestion,
220                                     t,
221                                     // The import probably needs to be changed
222                                     Applicability::MaybeIncorrect,
223                                 )
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::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
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                             fluent::lint_lintpass_by_hand,
314                             |lint| lint.help(fluent::help),
315                         )
316                     }
317                 }
318             }
319         }
320     }
321 }
322
323 declare_tool_lint! {
324     pub rustc::EXISTING_DOC_KEYWORD,
325     Allow,
326     "Check that documented keywords in std and core actually exist",
327     report_in_external_macro: true
328 }
329
330 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
331
332 fn is_doc_keyword(s: Symbol) -> bool {
333     s <= kw::Union
334 }
335
336 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
337     fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
338         for attr in cx.tcx.hir().attrs(item.hir_id()) {
339             if !attr.has_name(sym::doc) {
340                 continue;
341             }
342             if let Some(list) = attr.meta_item_list() {
343                 for nested in list {
344                     if nested.has_name(sym::keyword) {
345                         let v = nested
346                             .value_str()
347                             .expect("#[doc(keyword = \"...\")] expected a value!");
348                         if is_doc_keyword(v) {
349                             return;
350                         }
351                         cx.struct_span_lint(
352                             EXISTING_DOC_KEYWORD,
353                             attr.span,
354                             fluent::lint_non_existant_doc_keyword,
355                             |lint| lint.set_arg("keyword", v).help(fluent::help),
356                         );
357                     }
358                 }
359             }
360         }
361     }
362 }
363
364 declare_tool_lint! {
365     pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
366     Allow,
367     "prevent creation of diagnostics which cannot be translated",
368     report_in_external_macro: true
369 }
370
371 declare_tool_lint! {
372     pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
373     Allow,
374     "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
375     report_in_external_macro: true
376 }
377
378 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
379
380 impl LateLintPass<'_> for Diagnostics {
381     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
382         let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
383         debug!(?span, ?def_id, ?substs);
384         let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
385             .ok()
386             .and_then(|inst| inst)
387             .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
388             .unwrap_or(false);
389         if !has_attr {
390             return;
391         }
392
393         let mut found_parent_with_attr = false;
394         let mut found_impl = false;
395         for (hir_id, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
396             if let Some(owner_did) = hir_id.as_owner() {
397                 found_parent_with_attr = found_parent_with_attr
398                     || cx.tcx.has_attr(owner_did.to_def_id(), sym::rustc_lint_diagnostics);
399             }
400
401             debug!(?parent);
402             if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
403                 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
404                 let Some(def_id) = of_trait.trait_def_id() &&
405                 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
406                 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
407             {
408                 found_impl = true;
409                 break;
410             }
411         }
412         debug!(?found_impl);
413         if !found_parent_with_attr && !found_impl {
414             cx.struct_span_lint(
415                 DIAGNOSTIC_OUTSIDE_OF_IMPL,
416                 span,
417                 fluent::lint_diag_out_of_impl,
418                 |lint| lint,
419             )
420         }
421
422         let mut found_diagnostic_message = false;
423         for ty in substs.types() {
424             debug!(?ty);
425             if let Some(adt_def) = ty.ty_adt_def() &&
426                 let Some(name) =  cx.tcx.get_diagnostic_name(adt_def.did()) &&
427                 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
428             {
429                 found_diagnostic_message = true;
430                 break;
431             }
432         }
433         debug!(?found_diagnostic_message);
434         if !found_parent_with_attr && !found_diagnostic_message {
435             cx.struct_span_lint(
436                 UNTRANSLATABLE_DIAGNOSTIC,
437                 span,
438                 fluent::lint_untranslatable_diag,
439                 |lint| lint,
440             )
441         }
442     }
443 }
444
445 declare_tool_lint! {
446     pub rustc::BAD_OPT_ACCESS,
447     Deny,
448     "prevent using options by field access when there is a wrapper function",
449     report_in_external_macro: true
450 }
451
452 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
453
454 impl LateLintPass<'_> for BadOptAccess {
455     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
456         let ExprKind::Field(base, target) = expr.kind else { return };
457         let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
458         // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
459         // avoided.
460         if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
461             return;
462         }
463
464         for field in adt_def.all_fields() {
465             if field.name == target.name &&
466                 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
467                 let Some(items) = attr.meta_item_list()  &&
468                 let Some(item) = items.first()  &&
469                 let Some(literal) = item.literal()  &&
470                 let ast::LitKind::Str(val, _) = literal.kind
471             {
472                 cx.struct_span_lint(BAD_OPT_ACCESS, expr.span, val.as_str(), |lint|
473                     lint
474                 );
475             }
476         }
477     }
478 }