]> git.proxmox.com Git - rustc.git/blob - src/librustc_lint/internal.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_lint / 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::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
5 use rustc_ast::ast::{Ident, Item, ItemKind};
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_errors::Applicability;
8 use rustc_hir::{GenericArg, HirId, MutTy, Mutability, Path, PathSegment, QPath, Ty, TyKind};
9 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
10 use rustc_span::hygiene::{ExpnKind, MacroKind};
11 use rustc_span::symbol::{sym, Symbol};
12
13 declare_tool_lint! {
14 pub rustc::DEFAULT_HASH_TYPES,
15 Allow,
16 "forbid HashMap and HashSet and suggest the FxHash* variants",
17 report_in_external_macro: true
18 }
19
20 pub struct DefaultHashTypes {
21 map: FxHashMap<Symbol, Symbol>,
22 }
23
24 impl DefaultHashTypes {
25 // we are allowed to use `HashMap` and `HashSet` as identifiers for implementing the lint itself
26 #[allow(rustc::default_hash_types)]
27 pub fn new() -> Self {
28 let mut map = FxHashMap::default();
29 map.insert(sym::HashMap, sym::FxHashMap);
30 map.insert(sym::HashSet, sym::FxHashSet);
31 Self { map }
32 }
33 }
34
35 impl_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
36
37 impl EarlyLintPass for DefaultHashTypes {
38 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
39 if let Some(replace) = self.map.get(&ident.name) {
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 });
56 }
57 }
58 }
59
60 declare_tool_lint! {
61 pub rustc::USAGE_OF_TY_TYKIND,
62 Allow,
63 "usage of `ty::TyKind` outside of the `ty::sty` module",
64 report_in_external_macro: true
65 }
66
67 declare_tool_lint! {
68 pub rustc::TY_PASS_BY_REFERENCE,
69 Allow,
70 "passing `Ty` or `TyCtxt` by reference",
71 report_in_external_macro: true
72 }
73
74 declare_tool_lint! {
75 pub rustc::USAGE_OF_QUALIFIED_TY,
76 Allow,
77 "using `ty::{Ty,TyCtxt}` instead of importing it",
78 report_in_external_macro: true
79 }
80
81 declare_lint_pass!(TyTyKind => [
82 USAGE_OF_TY_TYKIND,
83 TY_PASS_BY_REFERENCE,
84 USAGE_OF_QUALIFIED_TY,
85 ]);
86
87 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TyTyKind {
88 fn check_path(&mut self, cx: &LateContext<'_, '_>, path: &'tcx Path<'tcx>, _: HirId) {
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) {
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 })
104 }
105 }
106 }
107
108 fn check_ty(&mut self, cx: &LateContext<'_, '_>, ty: &'tcx Ty<'tcx>) {
109 match &ty.kind {
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) {
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 })
119 } else {
120 if ty.span.from_expansion() {
121 return;
122 }
123 if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
124 if path.segments.len() > 1 {
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 })
136 }
137 }
138 }
139 }
140 }
141 }
142 TyKind::Rptr(_, MutTy { ty: inner_ty, mutbl: Mutability::Not }) => {
143 if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner.to_def_id()) {
144 if cx.tcx.impl_trait_ref(impl_did).is_some() {
145 return;
146 }
147 }
148 if let Some(t) = is_ty_or_ty_ctxt(cx, &inner_ty) {
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 })
160 }
161 }
162 _ => {}
163 }
164 }
165 }
166
167 fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment<'_>) -> bool {
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);
171 }
172 }
173
174 false
175 }
176
177 fn is_ty_or_ty_ctxt(cx: &LateContext<'_, '_>, ty: &Ty<'_>) -> Option<String> {
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())));
185 }
186 }
187 }
188
189 None
190 }
191
192 fn gen_args(segment: &PathSegment<'_>) -> String {
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 }
213
214 declare_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
220 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
221
222 impl EarlyLintPass for LintPassImpl {
223 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
224 if let ItemKind::Impl { of_trait: Some(lint_pass), .. } = &item.kind {
225 if let Some(last) = lint_pass.path.segments.last() {
226 if last.ident.name == sym::LintPass {
227 let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
228 let call_site = expn_data.call_site;
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 {
233 cx.struct_span_lint(
234 LINT_PASS_IMPL_WITHOUT_MACRO,
235 lint_pass.path.span,
236 |lint| {
237 lint.build("implementing `LintPass` by hand")
238 .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
239 .emit();
240 },
241 )
242 }
243 }
244 }
245 }
246 }
247 }