]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/internal.rs
Merge from rustc
[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 { Some(lt.ident.to_string()) } else { None }
276             })
277             .collect::<Vec<_>>();
278
279         if !lifetimes.is_empty() {
280             return format!("<{}>", lifetimes.join(", "));
281         }
282     }
283
284     String::new()
285 }
286
287 declare_tool_lint! {
288     pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
289     Allow,
290     "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
291 }
292
293 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
294
295 impl EarlyLintPass for LintPassImpl {
296     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
297         if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
298             if let Some(last) = lint_pass.path.segments.last() {
299                 if last.ident.name == sym::LintPass {
300                     let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
301                     let call_site = expn_data.call_site;
302                     if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
303                         && call_site.ctxt().outer_expn_data().kind
304                             != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
305                     {
306                         cx.struct_span_lint(
307                             LINT_PASS_IMPL_WITHOUT_MACRO,
308                             lint_pass.path.span,
309                             fluent::lint_lintpass_by_hand,
310                             |lint| lint.help(fluent::help),
311                         )
312                     }
313                 }
314             }
315         }
316     }
317 }
318
319 declare_tool_lint! {
320     pub rustc::EXISTING_DOC_KEYWORD,
321     Allow,
322     "Check that documented keywords in std and core actually exist",
323     report_in_external_macro: true
324 }
325
326 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
327
328 fn is_doc_keyword(s: Symbol) -> bool {
329     s <= kw::Union
330 }
331
332 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
333     fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
334         for attr in cx.tcx.hir().attrs(item.hir_id()) {
335             if !attr.has_name(sym::doc) {
336                 continue;
337             }
338             if let Some(list) = attr.meta_item_list() {
339                 for nested in list {
340                     if nested.has_name(sym::keyword) {
341                         let v = nested
342                             .value_str()
343                             .expect("#[doc(keyword = \"...\")] expected a value!");
344                         if is_doc_keyword(v) {
345                             return;
346                         }
347                         cx.struct_span_lint(
348                             EXISTING_DOC_KEYWORD,
349                             attr.span,
350                             fluent::lint_non_existant_doc_keyword,
351                             |lint| lint.set_arg("keyword", v).help(fluent::help),
352                         );
353                     }
354                 }
355             }
356         }
357     }
358 }
359
360 declare_tool_lint! {
361     pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
362     Allow,
363     "prevent creation of diagnostics which cannot be translated",
364     report_in_external_macro: true
365 }
366
367 declare_tool_lint! {
368     pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
369     Allow,
370     "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
371     report_in_external_macro: true
372 }
373
374 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
375
376 impl LateLintPass<'_> for Diagnostics {
377     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
378         let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
379         debug!(?span, ?def_id, ?substs);
380         let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
381             .ok()
382             .and_then(|inst| inst)
383             .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
384             .unwrap_or(false);
385         if !has_attr {
386             return;
387         }
388
389         let mut found_parent_with_attr = false;
390         let mut found_impl = false;
391         for (hir_id, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
392             if let Some(owner_did) = hir_id.as_owner() {
393                 found_parent_with_attr = found_parent_with_attr
394                     || cx.tcx.has_attr(owner_did.to_def_id(), sym::rustc_lint_diagnostics);
395             }
396
397             debug!(?parent);
398             if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
399                 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
400                 let Some(def_id) = of_trait.trait_def_id() &&
401                 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
402                 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
403             {
404                 found_impl = true;
405                 break;
406             }
407         }
408         debug!(?found_impl);
409         if !found_parent_with_attr && !found_impl {
410             cx.struct_span_lint(
411                 DIAGNOSTIC_OUTSIDE_OF_IMPL,
412                 span,
413                 fluent::lint_diag_out_of_impl,
414                 |lint| lint,
415             )
416         }
417
418         let mut found_diagnostic_message = false;
419         for ty in substs.types() {
420             debug!(?ty);
421             if let Some(adt_def) = ty.ty_adt_def() &&
422                 let Some(name) =  cx.tcx.get_diagnostic_name(adt_def.did()) &&
423                 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
424             {
425                 found_diagnostic_message = true;
426                 break;
427             }
428         }
429         debug!(?found_diagnostic_message);
430         if !found_parent_with_attr && !found_diagnostic_message {
431             cx.struct_span_lint(
432                 UNTRANSLATABLE_DIAGNOSTIC,
433                 span,
434                 fluent::lint_untranslatable_diag,
435                 |lint| lint,
436             )
437         }
438     }
439 }
440
441 declare_tool_lint! {
442     pub rustc::BAD_OPT_ACCESS,
443     Deny,
444     "prevent using options by field access when there is a wrapper function",
445     report_in_external_macro: true
446 }
447
448 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
449
450 impl LateLintPass<'_> for BadOptAccess {
451     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
452         let ExprKind::Field(base, target) = expr.kind else { return };
453         let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
454         // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
455         // avoided.
456         if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
457             return;
458         }
459
460         for field in adt_def.all_fields() {
461             if field.name == target.name &&
462                 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
463                 let Some(items) = attr.meta_item_list()  &&
464                 let Some(item) = items.first()  &&
465                 let Some(literal) = item.literal()  &&
466                 let ast::LitKind::Str(val, _) = literal.kind
467             {
468                 cx.struct_span_lint(BAD_OPT_ACCESS, expr.span, val.as_str(), |lint|
469                     lint
470                 );
471             }
472         }
473     }
474 }