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