]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_lint/src/internal.rs
New upstream version 1.56.0+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
dfeec247 4use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
136023e0 5use rustc_ast as ast;
dfeec247 6use rustc_errors::Applicability;
1b1a35ee 7use rustc_hir::def::Res;
136023e0
XL
8use rustc_hir::{
9 GenericArg, HirId, Item, ItemKind, MutTy, Mutability, Node, Path, PathSegment, QPath, Ty,
10 TyKind,
11};
1b1a35ee 12use rustc_middle::ty;
136023e0 13use rustc_session::{declare_lint_pass, declare_tool_lint};
dfeec247 14use rustc_span::hygiene::{ExpnKind, MacroKind};
136023e0 15use rustc_span::symbol::{kw, sym, Symbol};
532ac7d7 16
416331ca
XL
17declare_tool_lint! {
18 pub rustc::DEFAULT_HASH_TYPES,
532ac7d7 19 Allow,
dfeec247
XL
20 "forbid HashMap and HashSet and suggest the FxHash* variants",
21 report_in_external_macro: true
532ac7d7
XL
22}
23
136023e0
XL
24declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
25
26impl LateLintPass<'_> for DefaultHashTypes {
27 fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) {
28 let def_id = match path.res {
29 Res::Def(rustc_hir::def::DefKind::Struct, id) => id,
30 _ => return,
31 };
32 if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) {
33 // don't lint imports, only actual usages
34 return;
532ac7d7 35 }
136023e0
XL
36 let replace = if cx.tcx.is_diagnostic_item(sym::hashmap_type, def_id) {
37 "FxHashMap"
38 } else if cx.tcx.is_diagnostic_item(sym::hashset_type, def_id) {
39 "FxHashSet"
40 } else {
41 return;
42 };
43 cx.struct_span_lint(DEFAULT_HASH_TYPES, path.span, |lint| {
44 let msg = format!(
45 "prefer `{}` over `{}`, it has better performance",
46 replace,
47 cx.tcx.item_name(def_id)
48 );
49 lint.build(&msg)
50 .note(&format!("a `use rustc_data_structures::fx::{}` may be necessary", replace))
51 .emit();
52 });
532ac7d7
XL
53 }
54}
55
416331ca
XL
56declare_tool_lint! {
57 pub rustc::USAGE_OF_TY_TYKIND,
532ac7d7 58 Allow,
dfeec247
XL
59 "usage of `ty::TyKind` outside of the `ty::sty` module",
60 report_in_external_macro: true
532ac7d7
XL
61}
62
416331ca
XL
63declare_tool_lint! {
64 pub rustc::TY_PASS_BY_REFERENCE,
48663c56 65 Allow,
dfeec247
XL
66 "passing `Ty` or `TyCtxt` by reference",
67 report_in_external_macro: true
48663c56
XL
68}
69
416331ca
XL
70declare_tool_lint! {
71 pub rustc::USAGE_OF_QUALIFIED_TY,
48663c56 72 Allow,
dfeec247
XL
73 "using `ty::{Ty,TyCtxt}` instead of importing it",
74 report_in_external_macro: true
48663c56
XL
75}
76
77declare_lint_pass!(TyTyKind => [
78 USAGE_OF_TY_TYKIND,
79 TY_PASS_BY_REFERENCE,
80 USAGE_OF_QUALIFIED_TY,
81]);
532ac7d7 82
f035d41b
XL
83impl<'tcx> LateLintPass<'tcx> for TyTyKind {
84 fn check_path(&mut self, cx: &LateContext<'_>, path: &'tcx Path<'tcx>, _: HirId) {
532ac7d7
XL
85 let segments = path.segments.iter().rev().skip(1).rev();
86
87 if let Some(last) = segments.last() {
88 let span = path.span.with_hi(last.ident.span.hi());
89 if lint_ty_kind_usage(cx, last) {
74b04a01
XL
90 cx.struct_span_lint(USAGE_OF_TY_TYKIND, span, |lint| {
91 lint.build("usage of `ty::TyKind::<kind>`")
92 .span_suggestion(
93 span,
94 "try using ty::<kind> directly",
95 "ty".to_string(),
96 Applicability::MaybeIncorrect, // ty maybe needs an import
97 )
98 .emit();
99 })
532ac7d7
XL
100 }
101 }
102 }
103
f035d41b 104 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
e74abb32 105 match &ty.kind {
48663c56
XL
106 TyKind::Path(qpath) => {
107 if let QPath::Resolved(_, path) = qpath {
108 if let Some(last) = path.segments.iter().last() {
109 if lint_ty_kind_usage(cx, last) {
74b04a01
XL
110 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
111 lint.build("usage of `ty::TyKind`")
112 .help("try using `Ty` instead")
113 .emit();
114 })
48663c56 115 } else {
e1599b0c 116 if ty.span.from_expansion() {
48663c56
XL
117 return;
118 }
119 if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
120 if path.segments.len() > 1 {
74b04a01
XL
121 cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
122 lint.build(&format!("usage of qualified `ty::{}`", t))
123 .span_suggestion(
124 path.span,
125 "try using it unqualified",
126 t,
127 // The import probably needs to be changed
128 Applicability::MaybeIncorrect,
129 )
130 .emit();
131 })
48663c56
XL
132 }
133 }
134 }
135 }
136 }
137 }
dfeec247 138 TyKind::Rptr(_, MutTy { ty: inner_ty, mutbl: Mutability::Not }) => {
ba9703b0 139 if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner.to_def_id()) {
48663c56
XL
140 if cx.tcx.impl_trait_ref(impl_did).is_some() {
141 return;
532ac7d7
XL
142 }
143 }
48663c56 144 if let Some(t) = is_ty_or_ty_ctxt(cx, &inner_ty) {
74b04a01
XL
145 cx.struct_span_lint(TY_PASS_BY_REFERENCE, ty.span, |lint| {
146 lint.build(&format!("passing `{}` by reference", t))
147 .span_suggestion(
148 ty.span,
149 "try passing by value",
150 t,
151 // Changing type of function argument
152 Applicability::MaybeIncorrect,
153 )
154 .emit();
155 })
48663c56 156 }
532ac7d7 157 }
48663c56 158 _ => {}
532ac7d7
XL
159 }
160 }
161}
162
f035d41b 163fn lint_ty_kind_usage(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> bool {
e1599b0c
XL
164 if let Some(res) = segment.res {
165 if let Some(did) = res.opt_def_id() {
166 return cx.tcx.is_diagnostic_item(sym::TyKind, did);
532ac7d7
XL
167 }
168 }
169
170 false
171}
48663c56 172
f035d41b 173fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, ty: &Ty<'_>) -> Option<String> {
ba9703b0
XL
174 if let TyKind::Path(qpath) = &ty.kind {
175 if let QPath::Resolved(_, path) = qpath {
1b1a35ee
XL
176 match path.res {
177 Res::Def(_, did) => {
178 if cx.tcx.is_diagnostic_item(sym::Ty, did) {
179 return Some(format!("Ty{}", gen_args(path.segments.last().unwrap())));
180 } else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) {
181 return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap())));
182 }
183 }
184 // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
185 Res::SelfTy(None, Some((did, _))) => {
186 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
187 if cx.tcx.is_diagnostic_item(sym::Ty, adt.did) {
188 // NOTE: This path is currently unreachable as `Ty<'tcx>` is
189 // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
190 // is not actually allowed.
191 //
192 // I(@lcnr) still kept this branch in so we don't miss this
193 // if we ever change it in the future.
194 return Some(format!("Ty<{}>", substs[0]));
195 } else if cx.tcx.is_diagnostic_item(sym::TyCtxt, adt.did) {
196 return Some(format!("TyCtxt<{}>", substs[0]));
197 }
198 }
199 }
200 _ => (),
48663c56
XL
201 }
202 }
48663c56
XL
203 }
204
205 None
206}
207
dfeec247 208fn gen_args(segment: &PathSegment<'_>) -> String {
48663c56
XL
209 if let Some(args) = &segment.args {
210 let lifetimes = args
211 .args
212 .iter()
213 .filter_map(|arg| {
214 if let GenericArg::Lifetime(lt) = arg {
215 Some(lt.name.ident().to_string())
216 } else {
217 None
218 }
219 })
220 .collect::<Vec<_>>();
221
222 if !lifetimes.is_empty() {
223 return format!("<{}>", lifetimes.join(", "));
224 }
225 }
226
227 String::new()
228}
416331ca
XL
229
230declare_tool_lint! {
231 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
232 Allow,
233 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
234}
235
236declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
237
238impl EarlyLintPass for LintPassImpl {
136023e0
XL
239 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
240 if let ast::ItemKind::Impl(box ast::ImplKind { of_trait: Some(lint_pass), .. }) = &item.kind
241 {
416331ca
XL
242 if let Some(last) = lint_pass.path.segments.last() {
243 if last.ident.name == sym::LintPass {
e1599b0c
XL
244 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
245 let call_site = expn_data.call_site;
136023e0
XL
246 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
247 && call_site.ctxt().outer_expn_data().kind
248 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
249 {
e1599b0c
XL
250 cx.struct_span_lint(
251 LINT_PASS_IMPL_WITHOUT_MACRO,
252 lint_pass.path.span,
74b04a01
XL
253 |lint| {
254 lint.build("implementing `LintPass` by hand")
255 .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
256 .emit();
257 },
e1599b0c 258 )
416331ca
XL
259 }
260 }
261 }
262 }
263 }
264}
fc512014
XL
265
266declare_tool_lint! {
267 pub rustc::EXISTING_DOC_KEYWORD,
268 Allow,
269 "Check that documented keywords in std and core actually exist",
270 report_in_external_macro: true
271}
272
273declare_lint_pass!(ExistingDocKeyword => [EXISTING_DOC_KEYWORD]);
274
275fn is_doc_keyword(s: Symbol) -> bool {
276 s <= kw::Union
277}
278
279impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword {
280 fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) {
6a06907d 281 for attr in cx.tcx.hir().attrs(item.hir_id()) {
fc512014
XL
282 if !attr.has_name(sym::doc) {
283 continue;
284 }
285 if let Some(list) = attr.meta_item_list() {
286 for nested in list {
287 if nested.has_name(sym::keyword) {
288 let v = nested
289 .value_str()
290 .expect("#[doc(keyword = \"...\")] expected a value!");
291 if is_doc_keyword(v) {
292 return;
293 }
294 cx.struct_span_lint(EXISTING_DOC_KEYWORD, attr.span, |lint| {
295 lint.build(&format!(
296 "Found non-existing keyword `{}` used in \
297 `#[doc(keyword = \"...\")]`",
298 v,
299 ))
300 .help("only existing keywords are allowed in core/std")
301 .emit();
302 });
303 }
304 }
305 }
306 }
307 }
308}