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