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 declare_clippy_lint! {
18 /// **What it does:** Checks for various things we like to keep tidy in clippy.
20 /// **Why is this bad?** We like to pretend we're an example of tidy code.
22 /// **Known problems:** None.
24 /// **Example:** Wrong ordering of the util::paths constants.
25 pub CLIPPY_LINTS_INTERNAL,
27 "various things that will negatively affect your clippy experience"
30 declare_clippy_lint! {
31 /// **What it does:** Ensures every lint is associated to a `LintPass`.
33 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
34 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
35 /// know the name of the lint.
37 /// **Known problems:** Only checks for lints associated using the `lint_array!`
42 /// declare_lint! { pub LINT_1, ... }
43 /// declare_lint! { pub LINT_2, ... }
44 /// declare_lint! { pub FORGOTTEN_LINT, ... }
47 /// impl LintPass for Pass {
48 /// fn get_lints(&self) -> LintArray {
49 /// lint_array![LINT_1, LINT_2]
50 /// // missing FORGOTTEN_LINT
54 pub LINT_WITHOUT_LINT_PASS,
56 "declaring a lint without associating it in a LintPass"
59 declare_clippy_lint! {
60 /// **What it does:** Checks for the presence of the default hash types "HashMap" or "HashSet"
61 /// and recommends the FxHash* variants.
63 /// **Why is this bad?** The FxHash variants have better performance
64 /// and we don't need any collision prevention in clippy.
65 pub DEFAULT_HASH_TYPES,
67 "forbid HashMap and HashSet and suggest the FxHash* variants"
70 declare_clippy_lint! {
71 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
72 /// variant of the function.
74 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
75 /// warning/error messages.
77 /// **Known problems:** None.
82 /// cx.span_lint(LINT_NAME, "message");
87 /// utils::span_lint(cx, LINT_NAME, "message");
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 node_id = cx.tcx.hir().hir_to_node_id(impl_item_refs[0].id.hir_id);
168 let body_id = cx.tcx.hir().body_owned_by(node_id);
169 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
175 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
176 for (lint_name, &lint_span) in &self.declared_lints {
177 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
178 // file points to "<rustc macros>".
179 // `compiletest-rs` thinks that's an error in a different file and
180 // just ignores it. This causes the test in compile-fail/lint_pass
181 // not able to capture the error.
182 // Therefore, we need to climb the macro expansion tree and find the
183 // actual span that invoked `declare_tool_lint!`:
184 let lint_span = lint_span
188 .map(|ei| ei.call_site)
189 .expect("unable to get call_site");
191 if !self.registered_lints.contains(lint_name) {
194 LINT_WITHOUT_LINT_PASS,
196 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
203 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
212 if let TyKind::Path(ref path) = inner.node {
213 if let Def::Struct(def_id) = cx.tables.qpath_def(path, inner.hir_id) {
214 return match_def_path(cx.tcx, def_id, &paths::LINT);
222 struct LintCollector<'a, 'tcx: 'a> {
223 output: &'a mut FxHashSet<Name>,
224 cx: &'a LateContext<'a, 'tcx>,
227 impl<'a, 'tcx: 'a> Visitor<'tcx> for LintCollector<'a, 'tcx> {
228 fn visit_expr(&mut self, expr: &'tcx Expr) {
229 walk_expr(self, expr);
232 fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
233 if path.segments.len() == 1 {
234 self.output.insert(path.segments[0].ident.name);
237 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
238 NestedVisitorMap::All(&self.cx.tcx.hir())
242 pub struct DefaultHashTypes {
243 map: FxHashMap<String, String>,
246 impl DefaultHashTypes {
247 pub fn default() -> Self {
248 let mut map = FxHashMap::default();
249 map.insert("HashMap".to_string(), "FxHashMap".to_string());
250 map.insert("HashSet".to_string(), "FxHashSet".to_string());
255 impl LintPass for DefaultHashTypes {
256 fn get_lints(&self) -> LintArray {
257 lint_array!(DEFAULT_HASH_TYPES)
260 fn name(&self) -> &'static str {
265 impl EarlyLintPass for DefaultHashTypes {
266 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) {
267 let ident_string = ident.to_string();
268 if let Some(replace) = self.map.get(&ident_string) {
270 "Prefer {} over {}, it has better performance \
271 and we don't need any collision prevention in clippy",
272 replace, ident_string
281 Applicability::MaybeIncorrect, // FxHashMap, ... needs another import
287 #[derive(Clone, Default)]
288 pub struct CompilerLintFunctions {
289 map: FxHashMap<String, String>,
292 impl CompilerLintFunctions {
293 pub fn new() -> Self {
294 let mut map = FxHashMap::default();
295 map.insert("span_lint".to_string(), "utils::span_lint".to_string());
296 map.insert("struct_span_lint".to_string(), "utils::span_lint".to_string());
297 map.insert("lint".to_string(), "utils::span_lint".to_string());
298 map.insert("span_lint_note".to_string(), "utils::span_note_and_lint".to_string());
299 map.insert("span_lint_help".to_string(), "utils::span_help_and_lint".to_string());
304 impl LintPass for CompilerLintFunctions {
305 fn get_lints(&self) -> LintArray {
306 lint_array!(COMPILER_LINT_FUNCTIONS)
309 fn name(&self) -> &'static str {
310 "CompileLintFunctions"
314 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
315 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
317 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
318 let fn_name = path.ident.as_str().to_string();
319 if let Some(sugg) = self.map.get(&fn_name);
320 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
321 if match_type(cx, ty, &paths::EARLY_CONTEXT)
322 || match_type(cx, ty, &paths::LATE_CONTEXT);
326 COMPILER_LINT_FUNCTIONS,
328 "usage of a compiler lint function",
329 &format!("Please use the Clippy variant of this function: `{}`", sugg),