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