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