1 use crate::utils::{match_type, paths, span_help_and_lint, span_lint, walk_ptrs_ty};
2 use if_chain::if_chain;
4 use rustc::hir::def::{DefKind, Res};
5 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
7 use rustc::lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintPass};
8 use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use syntax::ast::{Crate as AstCrate, ItemKind, Name};
11 use syntax::source_map::Span;
12 use syntax::symbol::LocalInternedString;
14 declare_clippy_lint! {
15 /// **What it does:** Checks for various things we like to keep tidy in clippy.
17 /// **Why is this bad?** We like to pretend we're an example of tidy code.
19 /// **Known problems:** None.
21 /// **Example:** Wrong ordering of the util::paths constants.
22 pub CLIPPY_LINTS_INTERNAL,
24 "various things that will negatively affect your clippy experience"
27 declare_clippy_lint! {
28 /// **What it does:** Ensures every lint is associated to a `LintPass`.
30 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
31 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
32 /// know the name of the lint.
34 /// **Known problems:** Only checks for lints associated using the
35 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
39 /// declare_lint! { pub LINT_1, ... }
40 /// declare_lint! { pub LINT_2, ... }
41 /// declare_lint! { pub FORGOTTEN_LINT, ... }
43 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
44 /// // missing FORGOTTEN_LINT
46 pub LINT_WITHOUT_LINT_PASS,
48 "declaring a lint without associating it in a LintPass"
51 declare_clippy_lint! {
52 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
53 /// variant of the function.
55 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
56 /// warning/error messages.
58 /// **Known problems:** None.
63 /// cx.span_lint(LINT_NAME, "message");
68 /// utils::span_lint(cx, LINT_NAME, "message");
70 pub COMPILER_LINT_FUNCTIONS,
72 "usage of the lint functions of the compiler instead of the utils::* variant"
75 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
77 impl EarlyLintPass for ClippyLintsInternal {
78 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
79 if let Some(utils) = krate.module.items.iter().find(|item| item.ident.name == "utils") {
80 if let ItemKind::Mod(ref utils_mod) = utils.node {
81 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name == "paths") {
82 if let ItemKind::Mod(ref paths_mod) = paths.node {
83 let mut last_name: Option<LocalInternedString> = None;
84 for item in &paths_mod.items {
85 let name = item.ident.as_str();
86 if let Some(ref last_name) = last_name {
87 if **last_name > *name {
90 CLIPPY_LINTS_INTERNAL,
92 "this constant should be before the previous constant due to lexical \
97 last_name = Some(name);
106 #[derive(Clone, Debug, Default)]
107 pub struct LintWithoutLintPass {
108 declared_lints: FxHashMap<Name, Span>,
109 registered_lints: FxHashSet<Name>,
112 impl_lint_pass!(LintWithoutLintPass => [LINT_WITHOUT_LINT_PASS]);
114 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
115 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
116 if let hir::ItemKind::Static(ref ty, MutImmutable, _) = item.node {
117 if is_lint_ref_type(cx, ty) {
118 self.declared_lints.insert(item.ident.name, item.span);
120 } else if let hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) = item.node {
122 if let hir::TraitRef{path, ..} = trait_ref;
123 if let Res::Def(DefKind::Trait, def_id) = path.res;
124 if cx.match_def_path(def_id, &paths::LINT_PASS);
126 let mut collector = LintCollector {
127 output: &mut self.registered_lints,
130 let body_id = cx.tcx.hir().body_owned_by(
133 .find(|iiref| iiref.ident.as_str() == "get_lints")
134 .expect("LintPass needs to implement get_lints")
137 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
143 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
144 for (lint_name, &lint_span) in &self.declared_lints {
145 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
146 // file points to "<rustc macros>".
147 // `compiletest-rs` thinks that's an error in a different file and
148 // just ignores it. This causes the test in compile-fail/lint_pass
149 // not able to capture the error.
150 // Therefore, we need to climb the macro expansion tree and find the
151 // actual span that invoked `declare_tool_lint!`:
152 let lint_span = lint_span
156 .map(|ei| ei.call_site)
157 .expect("unable to get call_site");
159 if !self.registered_lints.contains(lint_name) {
162 LINT_WITHOUT_LINT_PASS,
164 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
171 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
180 if let TyKind::Path(ref path) = inner.node {
181 if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
182 return cx.match_def_path(def_id, &paths::LINT);
190 struct LintCollector<'a, 'tcx: 'a> {
191 output: &'a mut FxHashSet<Name>,
192 cx: &'a LateContext<'a, 'tcx>,
195 impl<'a, 'tcx: 'a> Visitor<'tcx> for LintCollector<'a, 'tcx> {
196 fn visit_expr(&mut self, expr: &'tcx Expr) {
197 walk_expr(self, expr);
200 fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
201 if path.segments.len() == 1 {
202 self.output.insert(path.segments[0].ident.name);
205 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
206 NestedVisitorMap::All(&self.cx.tcx.hir())
210 #[derive(Clone, Default)]
211 pub struct CompilerLintFunctions {
212 map: FxHashMap<String, String>,
215 impl CompilerLintFunctions {
216 pub fn new() -> Self {
217 let mut map = FxHashMap::default();
218 map.insert("span_lint".to_string(), "utils::span_lint".to_string());
219 map.insert("struct_span_lint".to_string(), "utils::span_lint".to_string());
220 map.insert("lint".to_string(), "utils::span_lint".to_string());
221 map.insert("span_lint_note".to_string(), "utils::span_note_and_lint".to_string());
222 map.insert("span_lint_help".to_string(), "utils::span_help_and_lint".to_string());
227 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
229 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
230 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
232 if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
233 let fn_name = path.ident.as_str().to_string();
234 if let Some(sugg) = self.map.get(&fn_name);
235 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
236 if match_type(cx, ty, &paths::EARLY_CONTEXT)
237 || match_type(cx, ty, &paths::LATE_CONTEXT);
241 COMPILER_LINT_FUNCTIONS,
243 "usage of a compiler lint function",
244 &format!("please use the Clippy variant of this function: `{}`", sugg),