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