2 match_def_path, match_type, paths, span_help_and_lint, span_lint, span_lint_and_sugg, walk_ptrs_ty,
4 use if_chain::if_chain;
6 use rustc::hir::def::Def;
7 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
9 use rustc::lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::{declare_tool_lint, lint_array};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::Applicability;
13 use syntax::ast::{Crate as AstCrate, Ident, ItemKind, Name};
14 use syntax::source_map::Span;
15 use syntax::symbol::LocalInternedString;
17 /// **What it does:** Checks for various things we like to keep tidy in clippy.
19 /// **Why is this bad?** We like to pretend we're an example of tidy code.
21 /// **Known problems:** None.
23 /// **Example:** Wrong ordering of the util::paths constants.
24 declare_clippy_lint! {
25 pub CLIPPY_LINTS_INTERNAL,
27 "various things that will negatively affect your clippy experience"
30 /// **What it does:** Ensures every lint is associated to a `LintPass`.
32 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
33 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
34 /// know the name of the lint.
36 /// **Known problems:** Only checks for lints associated using the `lint_array!`
41 /// declare_lint! { pub LINT_1, ... }
42 /// declare_lint! { pub LINT_2, ... }
43 /// declare_lint! { pub FORGOTTEN_LINT, ... }
46 /// impl LintPass for Pass {
47 /// fn get_lints(&self) -> LintArray {
48 /// lint_array![LINT_1, LINT_2]
49 /// // missing FORGOTTEN_LINT
53 declare_clippy_lint! {
54 pub LINT_WITHOUT_LINT_PASS,
56 "declaring a lint without associating it in a LintPass"
59 /// **What it does:** Checks for the presence of the default hash types "HashMap" or "HashSet"
60 /// and recommends the FxHash* variants.
62 /// **Why is this bad?** The FxHash variants have better performance
63 /// and we don't need any collision prevention in clippy.
64 declare_clippy_lint! {
65 pub DEFAULT_HASH_TYPES,
67 "forbid HashMap and HashSet and suggest the FxHash* variants"
70 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
71 /// variant of the function.
73 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
74 /// warning/error messages.
76 /// **Known problems:** None.
81 /// cx.span_lint(LINT_NAME, "message");
86 /// utils::span_lint(cx, LINT_NAME, "message");
88 declare_clippy_lint! {
89 pub COMPILER_LINT_FUNCTIONS,
91 "usage of the lint functions of the compiler instead of the utils::* variant"
94 #[derive(Copy, Clone)]
97 impl LintPass for Clippy {
98 fn get_lints(&self) -> LintArray {
99 lint_array!(CLIPPY_LINTS_INTERNAL)
102 fn name(&self) -> &'static str {
103 "ClippyLintsInternal"
107 impl EarlyLintPass for Clippy {
108 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
109 if let Some(utils) = krate.module.items.iter().find(|item| item.ident.name == "utils") {
110 if let ItemKind::Mod(ref utils_mod) = utils.node {
111 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name == "paths") {
112 if let ItemKind::Mod(ref paths_mod) = paths.node {
113 let mut last_name: Option<LocalInternedString> = None;
114 for item in &paths_mod.items {
115 let name = item.ident.as_str();
116 if let Some(ref last_name) = last_name {
117 if **last_name > *name {
120 CLIPPY_LINTS_INTERNAL,
122 "this constant should be before the previous constant due to lexical \
127 last_name = Some(name);
136 #[derive(Clone, Debug, Default)]
137 pub struct LintWithoutLintPass {
138 declared_lints: FxHashMap<Name, Span>,
139 registered_lints: FxHashSet<Name>,
142 impl LintPass for LintWithoutLintPass {
143 fn get_lints(&self) -> LintArray {
144 lint_array!(LINT_WITHOUT_LINT_PASS)
146 fn name(&self) -> &'static str {
147 "LintWithoutLintPass"
151 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
152 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
153 if let hir::ItemKind::Static(ref ty, MutImmutable, _) = item.node {
154 if is_lint_ref_type(cx, ty) {
155 self.declared_lints.insert(item.ident.name, item.span);
157 } else if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
159 if let hir::TraitRef{path, ..} = trait_ref;
160 if let Def::Trait(def_id) = path.def;
161 if match_def_path(cx.tcx, def_id, &paths::LINT_PASS);
163 let mut collector = LintCollector {
164 output: &mut self.registered_lints,
167 let body_id = cx.tcx.hir().body_owned_by(impl_item_refs[0].id.node_id);
168 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
174 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
175 for (lint_name, &lint_span) in &self.declared_lints {
176 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
177 // file points to "<rustc macros>".
178 // `compiletest-rs` thinks that's an error in a different file and
179 // just ignores it. This causes the test in compile-fail/lint_pass
180 // not able to capture the error.
181 // Therefore, we need to climb the macro expansion tree and find the
182 // actual span that invoked `declare_tool_lint!`:
183 let lint_span = lint_span
187 .map(|ei| ei.call_site)
188 .expect("unable to get call_site");
190 if !self.registered_lints.contains(lint_name) {
193 LINT_WITHOUT_LINT_PASS,
195 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
202 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
211 if let TyKind::Path(ref path) = inner.node {
212 if let Def::Struct(def_id) = cx.tables.qpath_def(path, inner.hir_id) {
213 return match_def_path(cx.tcx, def_id, &paths::LINT);
221 struct LintCollector<'a, 'tcx: 'a> {
222 output: &'a mut FxHashSet<Name>,
223 cx: &'a LateContext<'a, 'tcx>,
226 impl<'a, 'tcx: 'a> Visitor<'tcx> for LintCollector<'a, 'tcx> {
227 fn visit_expr(&mut self, expr: &'tcx Expr) {
228 walk_expr(self, expr);
231 fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
232 if path.segments.len() == 1 {
233 self.output.insert(path.segments[0].ident.name);
236 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
237 NestedVisitorMap::All(&self.cx.tcx.hir())
241 pub struct DefaultHashTypes {
242 map: FxHashMap<String, String>,
245 impl DefaultHashTypes {
246 pub fn default() -> Self {
247 let mut map = FxHashMap::default();
248 map.insert("HashMap".to_string(), "FxHashMap".to_string());
249 map.insert("HashSet".to_string(), "FxHashSet".to_string());
254 impl LintPass for DefaultHashTypes {
255 fn get_lints(&self) -> LintArray {
256 lint_array!(DEFAULT_HASH_TYPES)
259 fn name(&self) -> &'static str {
264 impl EarlyLintPass for DefaultHashTypes {
265 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
266 let ident_string = ident.to_string();
267 if let Some(replace) = self.map.get(&ident_string) {
269 "Prefer {} over {}, it has better performance \
270 and we don't need any collision prevention in clippy",
271 replace, ident_string
280 Applicability::MaybeIncorrect, // FxHashMap, ... needs another import
286 #[derive(Clone, Default)]
287 pub struct CompilerLintFunctions {
288 map: FxHashMap<String, String>,
291 impl CompilerLintFunctions {
292 pub fn new() -> Self {
293 let mut map = FxHashMap::default();
294 map.insert("span_lint".to_string(), "utils::span_lint".to_string());
295 map.insert("struct_span_lint".to_string(), "utils::span_lint".to_string());
296 map.insert("lint".to_string(), "utils::span_lint".to_string());
297 map.insert("span_lint_note".to_string(), "utils::span_note_and_lint".to_string());
298 map.insert("span_lint_help".to_string(), "utils::span_help_and_lint".to_string());
303 impl LintPass for CompilerLintFunctions {
304 fn get_lints(&self) -> LintArray {
305 lint_array!(COMPILER_LINT_FUNCTIONS)
308 fn name(&self) -> &'static str {
309 "CompileLintFunctions"
313 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
314 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
316 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
317 let fn_name = path.ident.as_str().to_string();
318 if let Some(sugg) = self.map.get(&fn_name);
319 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
320 if match_type(cx, ty, &paths::EARLY_CONTEXT)
321 || match_type(cx, ty, &paths::LATE_CONTEXT);
325 COMPILER_LINT_FUNCTIONS,
327 "usage of a compiler lint function",
328 &format!("Please use the Clippy variant of this function: `{}`", sugg),