]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/internal.rs
Rollup merge of #66498 - bjorn3:less_feature_flags, r=Dylan-DPC
[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::hygiene::{ExpnKind, MacroKind};
10 use rustc_span::symbol::{sym, Symbol};
11 use syntax::ast::{Ident, Item, ItemKind};
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             let msg = format!("Prefer {} over {}, it has better performance", replace, ident);
41             let mut db = cx.struct_span_lint(DEFAULT_HASH_TYPES, ident.span, &msg);
42             db.span_suggestion(
43                 ident.span,
44                 "use",
45                 replace.to_string(),
46                 Applicability::MaybeIncorrect, // FxHashMap, ... needs another import
47             );
48             db.note(&format!("a `use rustc_data_structures::fx::{}` may be necessary", replace))
49                 .emit();
50         }
51     }
52 }
53
54 declare_tool_lint! {
55     pub rustc::USAGE_OF_TY_TYKIND,
56     Allow,
57     "usage of `ty::TyKind` outside of the `ty::sty` module",
58     report_in_external_macro: true
59 }
60
61 declare_tool_lint! {
62     pub rustc::TY_PASS_BY_REFERENCE,
63     Allow,
64     "passing `Ty` or `TyCtxt` by reference",
65     report_in_external_macro: true
66 }
67
68 declare_tool_lint! {
69     pub rustc::USAGE_OF_QUALIFIED_TY,
70     Allow,
71     "using `ty::{Ty,TyCtxt}` instead of importing it",
72     report_in_external_macro: true
73 }
74
75 declare_lint_pass!(TyTyKind => [
76     USAGE_OF_TY_TYKIND,
77     TY_PASS_BY_REFERENCE,
78     USAGE_OF_QUALIFIED_TY,
79 ]);
80
81 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TyTyKind {
82     fn check_path(&mut self, cx: &LateContext<'_, '_>, path: &'tcx Path<'tcx>, _: HirId) {
83         let segments = path.segments.iter().rev().skip(1).rev();
84
85         if let Some(last) = segments.last() {
86             let span = path.span.with_hi(last.ident.span.hi());
87             if lint_ty_kind_usage(cx, last) {
88                 cx.struct_span_lint(USAGE_OF_TY_TYKIND, span, "usage of `ty::TyKind::<kind>`")
89                     .span_suggestion(
90                         span,
91                         "try using ty::<kind> directly",
92                         "ty".to_string(),
93                         Applicability::MaybeIncorrect, // ty maybe needs an import
94                     )
95                     .emit();
96             }
97         }
98     }
99
100     fn check_ty(&mut self, cx: &LateContext<'_, '_>, ty: &'tcx Ty<'tcx>) {
101         match &ty.kind {
102             TyKind::Path(qpath) => {
103                 if let QPath::Resolved(_, path) = qpath {
104                     if let Some(last) = path.segments.iter().last() {
105                         if lint_ty_kind_usage(cx, last) {
106                             cx.struct_span_lint(
107                                 USAGE_OF_TY_TYKIND,
108                                 path.span,
109                                 "usage of `ty::TyKind`",
110                             )
111                             .help("try using `Ty` instead")
112                             .emit();
113                         } else {
114                             if ty.span.from_expansion() {
115                                 return;
116                             }
117                             if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
118                                 if path.segments.len() > 1 {
119                                     cx.struct_span_lint(
120                                         USAGE_OF_QUALIFIED_TY,
121                                         path.span,
122                                         &format!("usage of qualified `ty::{}`", t),
123                                     )
124                                     .span_suggestion(
125                                         path.span,
126                                         "try using it unqualified",
127                                         t,
128                                         // The import probably needs to be changed
129                                         Applicability::MaybeIncorrect,
130                                     )
131                                     .emit();
132                                 }
133                             }
134                         }
135                     }
136                 }
137             }
138             TyKind::Rptr(_, MutTy { ty: inner_ty, mutbl: Mutability::Not }) => {
139                 if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner_def_id()) {
140                     if cx.tcx.impl_trait_ref(impl_did).is_some() {
141                         return;
142                     }
143                 }
144                 if let Some(t) = is_ty_or_ty_ctxt(cx, &inner_ty) {
145                     cx.struct_span_lint(
146                         TY_PASS_BY_REFERENCE,
147                         ty.span,
148                         &format!("passing `{}` by reference", t),
149                     )
150                     .span_suggestion(
151                         ty.span,
152                         "try passing by value",
153                         t,
154                         // Changing type of function argument
155                         Applicability::MaybeIncorrect,
156                     )
157                     .emit();
158                 }
159             }
160             _ => {}
161         }
162     }
163 }
164
165 fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment<'_>) -> bool {
166     if let Some(res) = segment.res {
167         if let Some(did) = res.opt_def_id() {
168             return cx.tcx.is_diagnostic_item(sym::TyKind, did);
169         }
170     }
171
172     false
173 }
174
175 fn is_ty_or_ty_ctxt(cx: &LateContext<'_, '_>, ty: &Ty<'_>) -> Option<String> {
176     match &ty.kind {
177         TyKind::Path(qpath) => {
178             if let QPath::Resolved(_, path) = qpath {
179                 let did = path.res.opt_def_id()?;
180                 if cx.tcx.is_diagnostic_item(sym::Ty, did) {
181                     return Some(format!("Ty{}", gen_args(path.segments.last().unwrap())));
182                 } else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) {
183                     return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap())));
184                 }
185             }
186         }
187         _ => {}
188     }
189
190     None
191 }
192
193 fn gen_args(segment: &PathSegment<'_>) -> String {
194     if let Some(args) = &segment.args {
195         let lifetimes = args
196             .args
197             .iter()
198             .filter_map(|arg| {
199                 if let GenericArg::Lifetime(lt) = arg {
200                     Some(lt.name.ident().to_string())
201                 } else {
202                     None
203                 }
204             })
205             .collect::<Vec<_>>();
206
207         if !lifetimes.is_empty() {
208             return format!("<{}>", lifetimes.join(", "));
209         }
210     }
211
212     String::new()
213 }
214
215 declare_tool_lint! {
216     pub rustc::LINT_PASS_IMPL_WITHOUT_MACRO,
217     Allow,
218     "`impl LintPass` without the `declare_lint_pass!` or `impl_lint_pass!` macros"
219 }
220
221 declare_lint_pass!(LintPassImpl => [LINT_PASS_IMPL_WITHOUT_MACRO]);
222
223 impl EarlyLintPass for LintPassImpl {
224     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
225         if let ItemKind::Impl { of_trait: Some(lint_pass), .. } = &item.kind {
226             if let Some(last) = lint_pass.path.segments.last() {
227                 if last.ident.name == sym::LintPass {
228                     let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
229                     let call_site = expn_data.call_site;
230                     if expn_data.kind != ExpnKind::Macro(MacroKind::Bang, sym::impl_lint_pass)
231                         && call_site.ctxt().outer_expn_data().kind
232                             != ExpnKind::Macro(MacroKind::Bang, sym::declare_lint_pass)
233                     {
234                         cx.struct_span_lint(
235                             LINT_PASS_IMPL_WITHOUT_MACRO,
236                             lint_pass.path.span,
237                             "implementing `LintPass` by hand",
238                         )
239                         .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
240                         .emit();
241                     }
242                 }
243             }
244         }
245     }
246 }