2 is_expn_of, match_def_path, match_type, method_calls, paths, span_help_and_lint, span_lint, span_lint_and_sugg,
5 use if_chain::if_chain;
7 use rustc::hir::def::{DefKind, Res};
8 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
10 use rustc::lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintPass};
11 use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_errors::Applicability;
15 use syntax::ast::{Crate as AstCrate, ItemKind, Name};
16 use syntax::source_map::Span;
17 use syntax::visit::FnKind;
18 use syntax_pos::symbol::SymbolStr;
20 declare_clippy_lint! {
21 /// **What it does:** Checks for various things we like to keep tidy in clippy.
23 /// **Why is this bad?** We like to pretend we're an example of tidy code.
25 /// **Known problems:** None.
27 /// **Example:** Wrong ordering of the util::paths constants.
28 pub CLIPPY_LINTS_INTERNAL,
30 "various things that will negatively affect your clippy experience"
33 declare_clippy_lint! {
34 /// **What it does:** Ensures every lint is associated to a `LintPass`.
36 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
37 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
38 /// know the name of the lint.
40 /// **Known problems:** Only checks for lints associated using the
41 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
45 /// declare_lint! { pub LINT_1, ... }
46 /// declare_lint! { pub LINT_2, ... }
47 /// declare_lint! { pub FORGOTTEN_LINT, ... }
49 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
50 /// // missing FORGOTTEN_LINT
52 pub LINT_WITHOUT_LINT_PASS,
54 "declaring a lint without associating it in a LintPass"
57 declare_clippy_lint! {
58 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
59 /// variant of the function.
61 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
62 /// warning/error messages.
64 /// **Known problems:** None.
69 /// cx.span_lint(LINT_NAME, "message");
74 /// utils::span_lint(cx, LINT_NAME, "message");
76 pub COMPILER_LINT_FUNCTIONS,
78 "usage of the lint functions of the compiler instead of the utils::* variant"
81 declare_clippy_lint! {
82 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
83 /// the `cx.outer_expn_data()`
85 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
87 /// **Known problems:** None.
92 /// expr.span.ctxt().outer().expn_data()
97 /// expr.span.ctxt().outer_expn_data()
99 pub OUTER_EXPN_EXPN_DATA,
101 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
104 declare_clippy_lint! {
105 /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
106 /// error message by calling `panic`.
108 /// **Why is this bad?** ICE in large quantities can damage your teeth
110 /// **Known problems:** None
119 "this message should not appear anywhere as we ICE before and don't emit the lint"
122 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
124 impl EarlyLintPass for ClippyLintsInternal {
125 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
126 if let Some(utils) = krate
130 .find(|item| item.ident.name.as_str() == "utils")
132 if let ItemKind::Mod(ref utils_mod) = utils.kind {
133 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
134 if let ItemKind::Mod(ref paths_mod) = paths.kind {
135 let mut last_name: Option<SymbolStr> = None;
136 for item in &*paths_mod.items {
137 let name = item.ident.as_str();
138 if let Some(ref last_name) = last_name {
139 if **last_name > *name {
142 CLIPPY_LINTS_INTERNAL,
144 "this constant should be before the previous constant due to lexical \
149 last_name = Some(name);
158 #[derive(Clone, Debug, Default)]
159 pub struct LintWithoutLintPass {
160 declared_lints: FxHashMap<Name, Span>,
161 registered_lints: FxHashSet<Name>,
164 impl_lint_pass!(LintWithoutLintPass => [LINT_WITHOUT_LINT_PASS]);
166 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LintWithoutLintPass {
167 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
168 if let hir::ItemKind::Static(ref ty, Mutability::Immutable, _) = item.kind {
169 if is_lint_ref_type(cx, ty) {
170 self.declared_lints.insert(item.ident.name, item.span);
172 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
173 || is_expn_of(item.span, "declare_lint_pass").is_some()
175 if let hir::ItemKind::Impl(.., None, _, ref impl_item_refs) = item.kind {
176 let mut collector = LintCollector {
177 output: &mut self.registered_lints,
180 let body_id = cx.tcx.hir().body_owned_by(
183 .find(|iiref| iiref.ident.as_str() == "get_lints")
184 .expect("LintPass needs to implement get_lints")
188 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
193 fn check_crate_post(&mut self, cx: &LateContext<'a, 'tcx>, _: &'tcx Crate) {
194 for (lint_name, &lint_span) in &self.declared_lints {
195 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
196 // file points to "<rustc macros>".
197 // `compiletest-rs` thinks that's an error in a different file and
198 // just ignores it. This causes the test in compile-fail/lint_pass
199 // not able to capture the error.
200 // Therefore, we need to climb the macro expansion tree and find the
201 // actual span that invoked `declare_tool_lint!`:
202 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
204 if !self.registered_lints.contains(lint_name) {
207 LINT_WITHOUT_LINT_PASS,
209 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
216 fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty) -> bool {
221 mutbl: Mutability::Immutable,
225 if let TyKind::Path(ref path) = inner.kind {
226 if let Res::Def(DefKind::Struct, def_id) = cx.tables.qpath_res(path, inner.hir_id) {
227 return match_def_path(cx, def_id, &paths::LINT);
235 struct LintCollector<'a, 'tcx> {
236 output: &'a mut FxHashSet<Name>,
237 cx: &'a LateContext<'a, 'tcx>,
240 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
241 fn visit_expr(&mut self, expr: &'tcx Expr) {
242 walk_expr(self, expr);
245 fn visit_path(&mut self, path: &'tcx Path, _: HirId) {
246 if path.segments.len() == 1 {
247 self.output.insert(path.segments[0].ident.name);
250 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
251 NestedVisitorMap::All(&self.cx.tcx.hir())
255 #[derive(Clone, Default)]
256 pub struct CompilerLintFunctions {
257 map: FxHashMap<&'static str, &'static str>,
260 impl CompilerLintFunctions {
262 pub fn new() -> Self {
263 let mut map = FxHashMap::default();
264 map.insert("span_lint", "utils::span_lint");
265 map.insert("struct_span_lint", "utils::span_lint");
266 map.insert("lint", "utils::span_lint");
267 map.insert("span_lint_note", "utils::span_note_and_lint");
268 map.insert("span_lint_help", "utils::span_help_and_lint");
273 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
275 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions {
276 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
278 if let ExprKind::MethodCall(ref path, _, ref args) = expr.kind;
279 let fn_name = path.ident;
280 if let Some(sugg) = self.map.get(&*fn_name.as_str());
281 let ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
282 if match_type(cx, ty, &paths::EARLY_CONTEXT)
283 || match_type(cx, ty, &paths::LATE_CONTEXT);
287 COMPILER_LINT_FUNCTIONS,
289 "usage of a compiler lint function",
290 &format!("please use the Clippy variant of this function: `{}`", sugg),
297 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
299 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass {
300 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
301 let (method_names, arg_lists, spans) = method_calls(expr, 2);
302 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
303 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
305 if let ["expn_data", "outer_expn"] = method_names.as_slice();
306 let args = arg_lists[1];
308 let self_arg = &args[0];
309 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(self_arg));
310 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
314 OUTER_EXPN_EXPN_DATA,
315 spans[1].with_hi(expr.span.hi()),
316 "usage of `outer_expn().expn_data()`",
318 "outer_expn_data()".to_string(),
319 Applicability::MachineApplicable,
326 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
328 impl EarlyLintPass for ProduceIce {
329 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: &ast::FnDecl, _: Span, _: ast::NodeId) {
330 if is_trigger_fn(fn_kind) {
331 panic!("Testing the ICE message");
336 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
338 FnKind::ItemFn(ident, ..) | FnKind::Method(ident, ..) => {
339 ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy"
341 FnKind::Closure(..) => false,