]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_lint/src/internal.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_lint / src / internal.rs
CommitLineData
532ac7d7
XL
1//! Some lints that are only useful in the compiler or crates that use compiler internals, such as
2//! Clippy.
3
9c376795
FG
4use crate::lints::{
5 BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand, NonExistantDocKeyword,
6 QueryInstability, TyQualified, TykindDiag, TykindKind, UntranslatableDiag,
7};
dfeec247 8use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
136023e0 9use rustc_ast as ast;
1b1a35ee 10use rustc_hir::def::Res;
923072b8
FG
11use rustc_hir::{def_id::DefId, Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath};
12use rustc_hir::{HirId, Impl, Item, ItemKind, Node, Pat, Ty, TyKind};
1b1a35ee 13use rustc_middle::ty;
136023e0 14use rustc_session::{declare_lint_pass, declare_tool_lint};
dfeec247 15use rustc_span::hygiene::{ExpnKind, MacroKind};
136023e0 16use rustc_span::symbol::{kw, sym, Symbol};
923072b8 17use rustc_span::Span;
532ac7d7 18
416331ca
XL
19declare_tool_lint! {
20 pub rustc::DEFAULT_HASH_TYPES,
532ac7d7 21 Allow,
dfeec247
XL
22 "forbid HashMap and HashSet and suggest the FxHash* variants",
23 report_in_external_macro: true
532ac7d7
XL
24}
25
136023e0
XL
26declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
27
28impl LateLintPass<'_> for DefaultHashTypes {
29 fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
5e7ed085 30 let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return };
136023e0
XL
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;
532ac7d7 34 }
9c376795 35 let preferred = match cx.tcx.get_diagnostic_name(def_id) {
c295e0f8
XL
36 Some(sym::HashMap) => "FxHashMap",
37 Some(sym::HashSet) => "FxHashSet",
38 _ => return,
136023e0 39 };
9c376795 40 cx.emit_spanned_lint(
2b03887a
FG
41 DEFAULT_HASH_TYPES,
42 path.span,
9c376795 43 DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) },
2b03887a 44 );
532ac7d7
XL
45 }
46}
47
923072b8
FG
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.
50fn typeck_results_of_method_fn<'tcx>(
51 cx: &LateContext<'tcx>,
52 expr: &Expr<'_>,
53) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)> {
923072b8 54 match expr.kind {
f2b60f7d 55 ExprKind::MethodCall(segment, ..)
923072b8
FG
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
416331ca 69declare_tool_lint! {
5099ac24 70 pub rustc::POTENTIAL_QUERY_INSTABILITY,
532ac7d7 71 Allow,
5099ac24 72 "require explicit opt-in when using potentially unstable methods or functions",
dfeec247 73 report_in_external_macro: true
532ac7d7
XL
74}
75
5099ac24
FG
76declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]);
77
78impl LateLintPass<'_> for QueryStability {
79 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
923072b8 80 let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return };
5099ac24
FG
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) {
9c376795 84 cx.emit_spanned_lint(
2b03887a
FG
85 POTENTIAL_QUERY_INSTABILITY,
86 span,
9c376795
FG
87 QueryInstability { query: cx.tcx.item_name(def_id) },
88 );
5099ac24
FG
89 }
90 }
91 }
92}
93
416331ca 94declare_tool_lint! {
5099ac24 95 pub rustc::USAGE_OF_TY_TYKIND,
48663c56 96 Allow,
5099ac24 97 "usage of `ty::TyKind` outside of the `ty::sty` module",
dfeec247 98 report_in_external_macro: true
48663c56
XL
99}
100
416331ca
XL
101declare_tool_lint! {
102 pub rustc::USAGE_OF_QUALIFIED_TY,
48663c56 103 Allow,
dfeec247
XL
104 "using `ty::{Ty,TyCtxt}` instead of importing it",
105 report_in_external_macro: true
48663c56
XL
106}
107
108declare_lint_pass!(TyTyKind => [
109 USAGE_OF_TY_TYKIND,
48663c56
XL
110 USAGE_OF_QUALIFIED_TY,
111]);
532ac7d7 112
f035d41b 113impl<'tcx> LateLintPass<'tcx> for TyTyKind {
923072b8
FG
114 fn check_path(
115 &mut self,
116 cx: &LateContext<'tcx>,
487cf647 117 path: &rustc_hir::Path<'tcx>,
923072b8
FG
118 _: rustc_hir::HirId,
119 ) {
120 if let Some(segment) = path.segments.iter().nth_back(1)
f2b60f7d 121 && lint_ty_kind_usage(cx, &segment.res)
923072b8
FG
122 {
123 let span = path.span.with_hi(
124 segment.args.map_or(segment.ident.span, |a| a.span_ext).hi()
125 );
9c376795
FG
126 cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
127 suggestion: span,
923072b8 128 });
532ac7d7
XL
129 }
130 }
131
f035d41b 132 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
e74abb32 133 match &ty.kind {
3c0e092e 134 TyKind::Path(QPath::Resolved(_, path)) => {
923072b8 135 if lint_ty_kind_usage(cx, &path.res) {
2b03887a 136 let hir = cx.tcx.hir();
9c376795 137 let span = match hir.find_parent(ty.hir_id) {
2b03887a
FG
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
923072b8 151 }
2b03887a
FG
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
48663c56 163 }
2b03887a
FG
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
923072b8 177 }
48663c56 178 }
2b03887a
FG
179 _ => None
180 };
181
182 match span {
183 Some(span) => {
9c376795
FG
184 cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind {
185 suggestion: span,
186 });
2b03887a 187 },
9c376795 188 None => cx.emit_spanned_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag),
48663c56 189 }
9c376795
FG
190 } else if !ty.span.from_expansion() && path.segments.len() > 1 && let Some(ty) = is_ty_or_ty_ctxt(cx, &path) {
191 cx.emit_spanned_lint(USAGE_OF_QUALIFIED_TY, path.span, TyQualified {
192 ty,
193 suggestion: path.span,
194 });
48663c56
XL
195 }
196 }
48663c56 197 _ => {}
532ac7d7
XL
198 }
199 }
200}
201
923072b8
FG
202fn 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
532ac7d7 207 }
532ac7d7 208}
48663c56 209
923072b8
FG
210fn 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())));
3c0e092e 215 }
923072b8
FG
216 }
217 // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
2b03887a 218 Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => {
923072b8
FG
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]));
1b1a35ee 229 }
48663c56
XL
230 }
231 }
923072b8 232 _ => (),
48663c56
XL
233 }
234
235 None
236}
237
dfeec247 238fn gen_args(segment: &PathSegment<'_>) -> String {
48663c56
XL
239 if let Some(args) = &segment.args {
240 let lifetimes = args
241 .args
242 .iter()
243 .filter_map(|arg| {
487cf647 244 if let GenericArg::Lifetime(lt) = arg { Some(lt.ident.to_string()) } else { None }
48663c56
XL
245 })
246 .collect::<Vec<_>>();
247
248 if !lifetimes.is_empty() {
249 return format!("<{}>", lifetimes.join(", "));
250 }
251 }
252
253 String::new()
254}
416331ca
XL
255
256declare_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
262declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
263
264impl EarlyLintPass for LintPassImpl {
136023e0 265 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
3c0e092e 266 if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
416331ca
XL
267 if let Some(last) = lint_pass.path.segments.last() {
268 if last.ident.name == sym::LintPass {
e1599b0c
XL
269 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
270 let call_site = expn_data.call_site;
136023e0
XL
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 {
9c376795 275 cx.emit_spanned_lint(
e1599b0c
XL
276 LINT_PASS_IMPL_WITHOUT_MACRO,
277 lint_pass.path.span,
9c376795
FG
278 LintPassByHand,
279 );
416331ca
XL
280 }
281 }
282 }
283 }
284 }
285}
fc512014
XL
286
287declare_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
294declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
295
296fn is_doc_keyword(s: Symbol) -> bool {
297 s <= kw::Union
298}
299
300impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
301 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
6a06907d 302 for attr in cx.tcx.hir().attrs(item.hir_id()) {
fc512014
XL
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) {
9c376795 309 let keyword = nested
fc512014
XL
310 .value_str()
311 .expect("#[doc(keyword = \"...\")] expected a value!");
9c376795 312 if is_doc_keyword(keyword) {
fc512014
XL
313 return;
314 }
9c376795 315 cx.emit_spanned_lint(
2b03887a
FG
316 EXISTING_DOC_KEYWORD,
317 attr.span,
9c376795 318 NonExistantDocKeyword { keyword },
2b03887a 319 );
fc512014
XL
320 }
321 }
322 }
323 }
324 }
325}
923072b8
FG
326
327declare_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
334declare_tool_lint! {
335 pub rustc::DIAGNOSTIC_OUTSIDE_OF_IMPL,
336 Allow,
2b03887a 337 "prevent creation of diagnostics outside of `IntoDiagnostic`/`AddToDiagnostic` impls",
923072b8
FG
338 report_in_external_macro: true
339}
340
341declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSIDE_OF_IMPL ]);
342
343impl 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);
064997fb
FG
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 {
923072b8
FG
353 return;
354 }
355
f2b60f7d 356 let mut found_parent_with_attr = false;
923072b8 357 let mut found_impl = false;
f2b60f7d
FG
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
923072b8
FG
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) &&
2b03887a 369 matches!(name, sym::IntoDiagnostic | sym::AddToDiagnostic | sym::DecorateLint)
923072b8
FG
370 {
371 found_impl = true;
372 break;
373 }
374 }
375 debug!(?found_impl);
f2b60f7d 376 if !found_parent_with_attr && !found_impl {
9c376795 377 cx.emit_spanned_lint(DIAGNOSTIC_OUTSIDE_OF_IMPL, span, DiagOutOfImpl);
923072b8
FG
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);
f2b60f7d 392 if !found_parent_with_attr && !found_diagnostic_message {
9c376795 393 cx.emit_spanned_lint(UNTRANSLATABLE_DIAGNOSTIC, span, UntranslatableDiag);
923072b8
FG
394 }
395 }
396}
064997fb
FG
397
398declare_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
405declare_lint_pass!(BadOptAccess => [ BAD_OPT_ACCESS ]);
406
407impl 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() &&
487cf647
FG
422 let Some(lit) = item.lit() &&
423 let ast::LitKind::Str(val, _) = lit.kind
064997fb 424 {
9c376795
FG
425 cx.emit_spanned_lint(BAD_OPT_ACCESS, expr.span, BadOptAccessDiag {
426 msg: val.as_str(),
427 });
064997fb
FG
428 }
429 }
430 }
431}