]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/internal.rs
Unify Opaque/Projection handling in region outlives code
[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::lints::{
5     BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand, NonExistantDocKeyword,
6     QueryInstability, TyQualified, TykindDiag, TykindKind, UntranslatableDiag,
7 };
8 use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
9 use rustc_ast as ast;
10 use rustc_hir::def::Res;
11 use rustc_hir::{def_id::DefId, Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath};
12 use rustc_hir::{HirId, Impl, Item, ItemKind, Node, Pat, Ty, TyKind};
13 use rustc_middle::ty;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::hygiene::{ExpnKind, MacroKind};
16 use rustc_span::symbol::{kw, sym, Symbol};
17 use rustc_span::Span;
18
19 declare_tool_lint! {
20     pub rustc::DEFAULT_HASH_TYPES,
21     Allow,
22     "forbid HashMap and HashSet and suggest the FxHash* variants",
23     report_in_external_macro: true
24 }
25
26 declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
27
28 impl LateLintPass<'_> for DefaultHashTypes {
29     fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
30         let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
31         if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
32             // don't lint imports, only actual usages
33             return;
34         }
35         let preferred = match cx.tcx.get_diagnostic_name(def_id) {
36             Some(sym::HashMap) => "FxHashMap",
37             Some(sym::HashSet) => "FxHashSet",
38             _ => return,
39         };
40         cx.emit_spanned_lint(
41             DEFAULT_HASH_TYPES,
42             path.span,
43             DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) },
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.emit_spanned_lint(
85                     POTENTIAL_QUERY_INSTABILITY,
86                     span,
87                     QueryInstability { query: cx.tcx.item_name(def_id) },
88                 );
89             }
90         }
91     }
92 }
93
94 declare_tool_lint! {
95     pub rustc::USAGE_OF_TY_TYKIND,
96     Allow,
97     "usage of `ty::TyKind` outside of the `ty::sty` module",
98     report_in_external_macro: true
99 }
100
101 declare_tool_lint! {
102     pub rustc::USAGE_OF_QUALIFIED_TY,
103     Allow,
104     "using `ty::{Ty,TyCtxt}` instead of importing it",
105     report_in_external_macro: true
106 }
107
108 declare_lint_pass!(TyTyKind => [
109     USAGE_OF_TY_TYKIND,
110     USAGE_OF_QUALIFIED_TY,
111 ]);
112
113 impl<'tcx> LateLintPass<'tcx> for TyTyKind {
114     fn check_path(
115         &mut self,
116         cx: &LateContext<'tcx>,
117         path: &rustc_hir::Path<'tcx>,
118         _: rustc_hir::HirId,
119     ) {
120         if let Some(segment) = path.segments.iter().nth_back(1)
121         && lint_ty_kind_usage(cx, &segment.res)
122         {
123             let span = path.span.with_hi(
124                 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
125             );
126             cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
127                 suggestion: span,
128             });
129         }
130     }
131
132     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
133         match &ty.kind {
134             TyKind::Path(QPath::Resolved(_, path)) => {
135                 if lint_ty_kind_usage(cx, &path.res) {
136                     let hir = cx.tcx.hir();
137                     let span = match hir.find_parent(ty.hir_id) {
138                         Some(Node::Pat(Pat {
139                             kind:
140                                 PatKind::Path(qpath)
141                                 | PatKind::TupleStruct(qpath, ..)
142                                 | PatKind::Struct(qpath, ..),
143                             ..
144                         })) => {
145                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
146                                 && qpath_ty.hir_id == ty.hir_id
147                             {
148                                 Some(path.span)
149                             } else {
150                                 None
151                             }
152                         }
153                         Some(Node::Expr(Expr {
154                             kind: ExprKind::Path(qpath),
155                             ..
156                         })) => {
157                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
158                                 && qpath_ty.hir_id == ty.hir_id
159                             {
160                                 Some(path.span)
161                             } else {
162                                 None
163                             }
164                         }
165                         // Can't unify these two branches because qpath below is `&&` and above is `&`
166                         // and `A | B` paths don't play well together with adjustments, apparently.
167                         Some(Node::Expr(Expr {
168                             kind: ExprKind::Struct(qpath, ..),
169                             ..
170                         })) => {
171                             if let QPath::TypeRelative(qpath_ty, ..) = qpath
172                                 && qpath_ty.hir_id == ty.hir_id
173                             {
174                                 Some(path.span)
175                             } else {
176                                 None
177                             }
178                         }
179                         _ => None
180                     };
181
182                     match span {
183                         Some(span) => {
184                             cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
185                                 suggestion: span,
186                             });
187                         },
188                         None => cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
189                     }
190                 } else if !ty.span.from_expansion() && path.segments.len() > 1 && let Some(t) = is_ty_or_ty_ctxt(cx, &path) {
191                     cx.emit_spanned_lint(USAGE_OF_QUALIFIED_TY, path.span, TyQualified {
192                         ty: t.clone(),
193                         suggestion: path.span,
194                     });
195                 }
196             }
197             _ => {}
198         }
199     }
200 }
201
202 fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool {
203     if let Some(did) = res.opt_def_id() {
204         cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did)
205     } else {
206         false
207     }
208 }
209
210 fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> {
211     match &path.res {
212         Res::Def(_, def_id) => {
213             if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) {
214                 return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
215             }
216         }
217         // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
218         Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
219             if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
220                 if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did())
221                 {
222                     // NOTE: This path is currently unreachable as `Ty<'tcx>` is
223                     // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
224                     // is not actually allowed.
225                     //
226                     // I(@lcnr) still kept this branch in so we don't miss this
227                     // if we ever change it in the future.
228                     return Some(format!("{}<{}>", name, substs[0]));
229                 }
230             }
231         }
232         _ => (),
233     }
234
235     None
236 }
237
238 fn gen_args(segment: &PathSegment<'_>) -> String {
239     if let Some(args) = &segment.args {
240         let lifetimes = args
241             .args
242             .iter()
243             .filter_map(|arg| {
244                 if let GenericArg::Lifetime(lt) = arg { Some(lt.ident.to_string()) } else { None }
245             })
246             .collect::<Vec<_>>();
247
248         if !lifetimes.is_empty() {
249             return format!("<{}>", lifetimes.join(", "));
250         }
251     }
252
253     String::new()
254 }
255
256 declare_tool_lint! {
257     pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
258     Allow,
259     "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
260 }
261
262 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
263
264 impl EarlyLintPass for LintPassImpl {
265     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
266         if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
267             if let Some(last) = lint_pass.path.segments.last() {
268                 if last.ident.name == sym::LintPass {
269                     let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
270                     let call_site = expn_data.call_site;
271                     if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
272                         && call_site.ctxt().outer_expn_data().kind
273                             != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
274                     {
275                         cx.emit_spanned_lint(
276                             LINT_PASS_IMPL_WITHOUT_MACRO,
277                             lint_pass.path.span,
278                             LintPassByHand,
279                         );
280                     }
281                 }
282             }
283         }
284     }
285 }
286
287 declare_tool_lint! {
288     pub rustc::EXISTING_DOC_KEYWORD,
289     Allow,
290     "Check that documented keywords in std and core actually exist",
291     report_in_external_macro: true
292 }
293
294 declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
295
296 fn is_doc_keyword(s: Symbol) -> bool {
297     s <= kw::Union
298 }
299
300 impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
301     fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
302         for attr in cx.tcx.hir().attrs(item.hir_id()) {
303             if !attr.has_name(sym::doc) {
304                 continue;
305             }
306             if let Some(list) = attr.meta_item_list() {
307                 for nested in list {
308                     if nested.has_name(sym::keyword) {
309                         let keyword = nested
310                             .value_str()
311                             .expect("#[doc(keyword = \"...\")] expected a value!");
312                         if is_doc_keyword(keyword) {
313                             return;
314                         }
315                         cx.emit_spanned_lint(
316                             EXISTING_DOC_KEYWORD,
317                             attr.span,
318                             NonExistantDocKeyword { keyword },
319                         );
320                     }
321                 }
322             }
323         }
324     }
325 }
326
327 declare_tool_lint! {
328     pub rustc::UNTRANSLATABLE_DIAGNOSTIC,
329     Allow,
330     "prevent creation of diagnostics which cannot be translated",
331     report_in_external_macro: true
332 }
333
334 declare_tool_lint! {
335     pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
336     Allow,
337     "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
338     report_in_external_macro: true
339 }
340
341 declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
342
343 impl LateLintPass<'_> for Diagnostics {
344     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
345         let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
346         debug!(?span, ?def_id, ?substs);
347         let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs)
348             .ok()
349             .and_then(|inst| inst)
350             .map(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics))
351             .unwrap_or(false);
352         if !has_attr {
353             return;
354         }
355
356         let mut found_parent_with_attr = false;
357         let mut found_impl = false;
358         for (hir_id, parent) in cx.tcx.hir().parent_iter(expr.hir_id) {
359             if let Some(owner_did) = hir_id.as_owner() {
360                 found_parent_with_attr = found_parent_with_attr
361                     || cx.tcx.has_attr(owner_did.to_def_id(), sym::rustc_lint_diagnostics);
362             }
363
364             debug!(?parent);
365             if let Node::Item(Item { kind: ItemKind::Impl(impl_), .. }) = parent &&
366                 let Impl { of_trait: Some(of_trait), .. } = impl_ &&
367                 let Some(def_id) = of_trait.trait_def_id() &&
368                 let Some(name) = cx.tcx.get_diagnostic_name(def_id) &&
369                 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
370             {
371                 found_impl = true;
372                 break;
373             }
374         }
375         debug!(?found_impl);
376         if !found_parent_with_attr && !found_impl {
377             cx.emit_spanned_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, DiagOutOfImpl);
378         }
379
380         let mut found_diagnostic_message = false;
381         for ty in substs.types() {
382             debug!(?ty);
383             if let Some(adt_def) = ty.ty_adt_def() &&
384                 let Some(name) =  cx.tcx.get_diagnostic_name(adt_def.did()) &&
385                 matches!(name, sym::DiagnosticMessage | sym::SubdiagnosticMessage)
386             {
387                 found_diagnostic_message = true;
388                 break;
389             }
390         }
391         debug!(?found_diagnostic_message);
392         if !found_parent_with_attr && !found_diagnostic_message {
393             cx.emit_spanned_lint(UNTRANSLATABLE_DIAGNOSTIC, span, UntranslatableDiag);
394         }
395     }
396 }
397
398 declare_tool_lint! {
399     pub rustc::BAD_OPT_ACCESS,
400     Deny,
401     "prevent using options by field access when there is a wrapper function",
402     report_in_external_macro: true
403 }
404
405 declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
406
407 impl LateLintPass<'_> for BadOptAccess {
408     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
409         let ExprKind::Field(base, target) = expr.kind else { return };
410         let Some(adt_def) = cx.typeck_results().expr_ty(base).ty_adt_def() else { return };
411         // Skip types without `#[rustc_lint_opt_ty]` - only so that the rest of the lint can be
412         // avoided.
413         if !cx.tcx.has_attr(adt_def.did(), sym::rustc_lint_opt_ty) {
414             return;
415         }
416
417         for field in adt_def.all_fields() {
418             if field.name == target.name &&
419                 let Some(attr) = cx.tcx.get_attr(field.did, sym::rustc_lint_opt_deny_field_access) &&
420                 let Some(items) = attr.meta_item_list()  &&
421                 let Some(item) = items.first()  &&
422                 let Some(lit) = item.lit()  &&
423                 let ast::LitKind::Str(val, _) = lit.kind
424             {
425                 cx.emit_spanned_lint(BAD_OPT_ACCESS, expr.span, BadOptAccessDiag {
426                     msg: val.as_str(),
427                 });
428             }
429         }
430     }
431 }