]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/internal.rs
Rollup merge of #67784 - Mark-Simulacrum:residual-pad-integral, r=dtolnay
[rust.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_data_structures::fx::FxHashMap;
6 use rustc_errors::Applicability;
7 use rustc_hir::{GenericArg, HirId, MutTy, Mutability, Path, PathSegment, QPath, Ty, TyKind};
8 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
9 use rustc_span::symbol::{sym, Symbol};
10 use syntax::ast::{Ident, Item, ItemKind};
11
12 declare_tool_lint! {
13     pub rustc::DEFAULT_HASH_TYPES,
14     Allow,
15     "forbid HashMap and HashSet and suggest the FxHash* variants",
16     report_in_external_macro: true
17 }
18
19 pub struct DefaultHashTypes {
20     map: FxHashMap<Symbol, Symbol>,
21 }
22
23 impl DefaultHashTypes {
24     // we are allowed to use `HashMap` and `HashSet` as identifiers for implementing the lint itself
25     #[allow(rustc::default_hash_types)]
26     pub fn new() -> Self {
27         let mut map = FxHashMap::default();
28         map.insert(sym::HashMap, sym::FxHashMap);
29         map.insert(sym::HashSet, sym::FxHashSet);
30         Self { map }
31     }
32 }
33
34 impl_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]);
35
36 impl EarlyLintPass for DefaultHashTypes {
37     fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
38         if let Some(replace) = self.map.get(&ident.name) {
39             let msg = format!("Prefer {} over {}, it has better performance", replace, ident);
40             let mut db = cx.struct_span_lint(DEFAULT_HASH_TYPES, ident.span, &msg);
41             db.span_suggestion(
42                 ident.span,
43                 "use",
44                 replace.to_string(),
45                 Applicability::MaybeIncorrect, // FxHashMap, ... needs another import
46             );
47             db.note(&format!("a `use rustc_data_structures::fx::{}` may be necessary", replace))
48                 .emit();
49         }
50     }
51 }
52
53 declare_tool_lint! {
54     pub rustc::USAGE_OF_TY_TYKIND,
55     Allow,
56     "usage of `ty::TyKind` outside of the `ty::sty` module",
57     report_in_external_macro: true
58 }
59
60 declare_tool_lint! {
61     pub rustc::TY_PASS_BY_REFERENCE,
62     Allow,
63     "passing `Ty` or `TyCtxt` by reference",
64     report_in_external_macro: true
65 }
66
67 declare_tool_lint! {
68     pub rustc::USAGE_OF_QUALIFIED_TY,
69     Allow,
70     "using `ty::{Ty,TyCtxt}` instead of importing it",
71     report_in_external_macro: true
72 }
73
74 declare_lint_pass!(TyTyKind => [
75     USAGE_OF_TY_TYKIND,
76     TY_PASS_BY_REFERENCE,
77     USAGE_OF_QUALIFIED_TY,
78 ]);
79
80 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TyTyKind {
81     fn check_path(&mut self, cx: &LateContext<'_, '_>, path: &'tcx Path<'tcx>, _: HirId) {
82         let segments = path.segments.iter().rev().skip(1).rev();
83
84         if let Some(last) = segments.last() {
85             let span = path.span.with_hi(last.ident.span.hi());
86             if lint_ty_kind_usage(cx, last) {
87                 cx.struct_span_lint(USAGE_OF_TY_TYKIND, span, "usage of `ty::TyKind::<kind>`")
88                     .span_suggestion(
89                         span,
90                         "try using ty::<kind> directly",
91                         "ty".to_string(),
92                         Applicability::MaybeIncorrect, // ty maybe needs an import
93                     )
94                     .emit();
95             }
96         }
97     }
98
99     fn check_ty(&mut self, cx: &LateContext<'_, '_>, ty: &'tcx Ty<'tcx>) {
100         match &ty.kind {
101             TyKind::Path(qpath) => {
102                 if let QPath::Resolved(_, path) = qpath {
103                     if let Some(last) = path.segments.iter().last() {
104                         if lint_ty_kind_usage(cx, last) {
105                             cx.struct_span_lint(
106                                 USAGE_OF_TY_TYKIND,
107                                 path.span,
108                                 "usage of `ty::TyKind`",
109                             )
110                             .help("try using `Ty` instead")
111                             .emit();
112                         } else {
113                             if ty.span.from_expansion() {
114                                 return;
115                             }
116                             if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
117                                 if path.segments.len() > 1 {
118                                     cx.struct_span_lint(
119                                         USAGE_OF_QUALIFIED_TY,
120                                         path.span,
121                                         &format!("usage of qualified `ty::{}`", t),
122                                     )
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                                 }
132                             }
133                         }
134                     }
135                 }
136             }
137             TyKind::Rptr(_, MutTy { ty: inner_ty, mutbl: Mutability::Not }) => {
138                 if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner_def_id()) {
139                     if cx.tcx.impl_trait_ref(impl_did).is_some() {
140                         return;
141                     }
142                 }
143                 if let Some(t) = is_ty_or_ty_ctxt(cx, &inner_ty) {
144                     cx.struct_span_lint(
145                         TY_PASS_BY_REFERENCE,
146                         ty.span,
147                         &format!("passing `{}` by reference", t),
148                     )
149                     .span_suggestion(
150                         ty.span,
151                         "try passing by value",
152                         t,
153                         // Changing type of function argument
154                         Applicability::MaybeIncorrect,
155                     )
156                     .emit();
157                 }
158             }
159             _ => {}
160         }
161     }
162 }
163
164 fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment<'_>) -> bool {
165     if let Some(res) = segment.res {
166         if let Some(did) = res.opt_def_id() {
167             return cx.tcx.is_diagnostic_item(sym::TyKind, did);
168         }
169     }
170
171     false
172 }
173
174 fn is_ty_or_ty_ctxt(cx: &LateContext<'_, '_>, ty: &Ty<'_>) -> Option<String> {
175     match &ty.kind {
176         TyKind::Path(qpath) => {
177             if let QPath::Resolved(_, path) = qpath {
178                 let did = path.res.opt_def_id()?;
179                 if cx.tcx.is_diagnostic_item(sym::Ty, did) {
180                     return Some(format!("Ty{}", gen_args(path.segments.last().unwrap())));
181                 } else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) {
182                     return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap())));
183                 }
184             }
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(_, _, _, _, 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.descr() != sym::impl_lint_pass
230                         && call_site.ctxt().outer_expn_data().kind.descr() != sym::declare_lint_pass
231                     {
232                         cx.struct_span_lint(
233                             LINT_PASS_IMPL_WITHOUT_MACRO,
234                             lint_pass.path.span,
235                             "implementing `LintPass` by hand",
236                         )
237                         .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
238                         .emit();
239                     }
240                 }
241             }
242         }
243     }
244 }