]> git.proxmox.com Git - rustc.git/blame - src/librustc_lint/internal.rs
New upstream version 1.45.0+dfsg1
[rustc.git] / src / librustc_lint / 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};
f9f354fc 5use rustc_ast::ast::{Item, ItemKind};
532ac7d7 6use rustc_data_structures::fx::FxHashMap;
dfeec247
XL
7use rustc_errors::Applicability;
8use rustc_hir::{GenericArg, HirId, MutTy, Mutability, Path, PathSegment, QPath, Ty, TyKind};
9use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
10use rustc_span::hygiene::{ExpnKind, MacroKind};
f9f354fc 11use rustc_span::symbol::{sym, Ident, Symbol};
532ac7d7 12
416331ca
XL
13declare_tool_lint! {
14 pub rustc::DEFAULT_HASH_TYPES,
532ac7d7 15 Allow,
dfeec247
XL
16 "forbid HashMap and HashSet and suggest the FxHash* variants",
17 report_in_external_macro: true
532ac7d7
XL
18}
19
20pub struct DefaultHashTypes {
dc9dc135 21 map: FxHashMap<Symbol, Symbol>,
532ac7d7
XL
22}
23
24impl DefaultHashTypes {
dc9dc135 25 // we are allowed to use `HashMap` and `HashSet` as identifiers for implementing the lint itself
e1599b0c 26 #[allow(rustc::default_hash_types)]
532ac7d7
XL
27 pub fn new() -> Self {
28 let mut map = FxHashMap::default();
dc9dc135
XL
29 map.insert(sym::HashMap, sym::FxHashMap);
30 map.insert(sym::HashSet, sym::FxHashSet);
532ac7d7
XL
31 Self { map }
32 }
33}
34
35impl_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
36
37impl EarlyLintPass for DefaultHashTypes {
38 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
dc9dc135 39 if let Some(replace) = self.map.get(&ident.name) {
74b04a01
XL
40 cx.struct_span_lint(DEFAULT_HASH_TYPES, ident.span, |lint| {
41 // FIXME: We can avoid a copy here. Would require us to take String instead of &str.
42 let msg = format!("Prefer {} over {}, it has better performance", replace, ident);
43 lint.build(&msg)
44 .span_suggestion(
45 ident.span,
46 "use",
47 replace.to_string(),
48 Applicability::MaybeIncorrect, // FxHashMap, ... needs another import
49 )
50 .note(&format!(
51 "a `use rustc_data_structures::fx::{}` may be necessary",
52 replace
53 ))
54 .emit();
55 });
532ac7d7
XL
56 }
57 }
58}
59
416331ca
XL
60declare_tool_lint! {
61 pub rustc::USAGE_OF_TY_TYKIND,
532ac7d7 62 Allow,
dfeec247
XL
63 "usage of `ty::TyKind` outside of the `ty::sty` module",
64 report_in_external_macro: true
532ac7d7
XL
65}
66
416331ca
XL
67declare_tool_lint! {
68 pub rustc::TY_PASS_BY_REFERENCE,
48663c56 69 Allow,
dfeec247
XL
70 "passing `Ty` or `TyCtxt` by reference",
71 report_in_external_macro: true
48663c56
XL
72}
73
416331ca
XL
74declare_tool_lint! {
75 pub rustc::USAGE_OF_QUALIFIED_TY,
48663c56 76 Allow,
dfeec247
XL
77 "using `ty::{Ty,TyCtxt}` instead of importing it",
78 report_in_external_macro: true
48663c56
XL
79}
80
81declare_lint_pass!(TyTyKind => [
82 USAGE_OF_TY_TYKIND,
83 TY_PASS_BY_REFERENCE,
84 USAGE_OF_QUALIFIED_TY,
85]);
532ac7d7 86
48663c56 87impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TyTyKind {
dfeec247 88 fn check_path(&mut self, cx: &LateContext<'_, '_>, path: &'tcx Path<'tcx>, _: HirId) {
532ac7d7
XL
89 let segments = path.segments.iter().rev().skip(1).rev();
90
91 if let Some(last) = segments.last() {
92 let span = path.span.with_hi(last.ident.span.hi());
93 if lint_ty_kind_usage(cx, last) {
74b04a01
XL
94 cx.struct_span_lint(USAGE_OF_TY_TYKIND, span, |lint| {
95 lint.build("usage of `ty::TyKind::<kind>`")
96 .span_suggestion(
97 span,
98 "try using ty::<kind> directly",
99 "ty".to_string(),
100 Applicability::MaybeIncorrect, // ty maybe needs an import
101 )
102 .emit();
103 })
532ac7d7
XL
104 }
105 }
106 }
107
dfeec247 108 fn check_ty(&mut self, cx: &LateContext<'_, '_>, ty: &'tcx Ty<'tcx>) {
e74abb32 109 match &ty.kind {
48663c56
XL
110 TyKind::Path(qpath) => {
111 if let QPath::Resolved(_, path) = qpath {
112 if let Some(last) = path.segments.iter().last() {
113 if lint_ty_kind_usage(cx, last) {
74b04a01
XL
114 cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
115 lint.build("usage of `ty::TyKind`")
116 .help("try using `Ty` instead")
117 .emit();
118 })
48663c56 119 } else {
e1599b0c 120 if ty.span.from_expansion() {
48663c56
XL
121 return;
122 }
123 if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
124 if path.segments.len() > 1 {
74b04a01
XL
125 cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
126 lint.build(&format!("usage of qualified `ty::{}`", t))
127 .span_suggestion(
128 path.span,
129 "try using it unqualified",
130 t,
131 // The import probably needs to be changed
132 Applicability::MaybeIncorrect,
133 )
134 .emit();
135 })
48663c56
XL
136 }
137 }
138 }
139 }
140 }
141 }
dfeec247 142 TyKind::Rptr(_, MutTy { ty: inner_ty, mutbl: Mutability::Not }) => {
ba9703b0 143 if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner.to_def_id()) {
48663c56
XL
144 if cx.tcx.impl_trait_ref(impl_did).is_some() {
145 return;
532ac7d7
XL
146 }
147 }
48663c56 148 if let Some(t) = is_ty_or_ty_ctxt(cx, &inner_ty) {
74b04a01
XL
149 cx.struct_span_lint(TY_PASS_BY_REFERENCE, ty.span, |lint| {
150 lint.build(&format!("passing `{}` by reference", t))
151 .span_suggestion(
152 ty.span,
153 "try passing by value",
154 t,
155 // Changing type of function argument
156 Applicability::MaybeIncorrect,
157 )
158 .emit();
159 })
48663c56 160 }
532ac7d7 161 }
48663c56 162 _ => {}
532ac7d7
XL
163 }
164 }
165}
166
dfeec247 167fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment<'_>) -> bool {
e1599b0c
XL
168 if let Some(res) = segment.res {
169 if let Some(did) = res.opt_def_id() {
170 return cx.tcx.is_diagnostic_item(sym::TyKind, did);
532ac7d7
XL
171 }
172 }
173
174 false
175}
48663c56 176
dfeec247 177fn is_ty_or_ty_ctxt(cx: &LateContext<'_, '_>, ty: &Ty<'_>) -> Option<String> {
ba9703b0
XL
178 if let TyKind::Path(qpath) = &ty.kind {
179 if let QPath::Resolved(_, path) = qpath {
180 let did = path.res.opt_def_id()?;
181 if cx.tcx.is_diagnostic_item(sym::Ty, did) {
182 return Some(format!("Ty{}", gen_args(path.segments.last().unwrap())));
183 } else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) {
184 return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap())));
48663c56
XL
185 }
186 }
48663c56
XL
187 }
188
189 None
190}
191
dfeec247 192fn gen_args(segment: &PathSegment<'_>) -> String {
48663c56
XL
193 if let Some(args) = &segment.args {
194 let lifetimes = args
195 .args
196 .iter()
197 .filter_map(|arg| {
198 if let GenericArg::Lifetime(lt) = arg {
199 Some(lt.name.ident().to_string())
200 } else {
201 None
202 }
203 })
204 .collect::<Vec<_>>();
205
206 if !lifetimes.is_empty() {
207 return format!("<{}>", lifetimes.join(", "));
208 }
209 }
210
211 String::new()
212}
416331ca
XL
213
214declare_tool_lint! {
215 pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
216 Allow,
217 "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
218}
219
220declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
221
222impl EarlyLintPass for LintPassImpl {
223 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
dfeec247 224 if let ItemKind::Impl { of_trait: Some(lint_pass), .. } = &item.kind {
416331ca
XL
225 if let Some(last) = lint_pass.path.segments.last() {
226 if last.ident.name == sym::LintPass {
e1599b0c
XL
227 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
228 let call_site = expn_data.call_site;
dfeec247
XL
229 if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
230 && call_site.ctxt().outer_expn_data().kind
231 != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
232 {
e1599b0c
XL
233 cx.struct_span_lint(
234 LINT_PASS_IMPL_WITHOUT_MACRO,
235 lint_pass.path.span,
74b04a01
XL
236 |lint| {
237 lint.build("implementing `LintPass` by hand")
238 .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
239 .emit();
240 },
e1599b0c 241 )
416331ca
XL
242 }
243 }
244 }
245 }
246 }
247}