2 is_expn_of, match_def_path, match_qpath, match_type, method_calls, path_to_res, paths, qpath_res, run_lints,
3 snippet, span_lint, span_lint_and_help, span_lint_and_sugg, walk_ptrs_ty, SpanlessEq,
5 use if_chain::if_chain;
6 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, NodeId};
7 use rustc_ast::visit::FnKind;
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_errors::Applicability;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::hir_id::CRATE_HIR_ID;
13 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
14 use rustc_hir::{Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Node, Path, StmtKind, Ty, TyKind};
15 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
16 use rustc_middle::hir::map::Map;
17 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
18 use rustc_span::source_map::{Span, Spanned};
19 use rustc_span::symbol::{Symbol, SymbolStr};
21 use std::borrow::{Borrow, Cow};
23 declare_clippy_lint! {
24 /// **What it does:** Checks for various things we like to keep tidy in clippy.
26 /// **Why is this bad?** We like to pretend we're an example of tidy code.
28 /// **Known problems:** None.
30 /// **Example:** Wrong ordering of the util::paths constants.
31 pub CLIPPY_LINTS_INTERNAL,
33 "various things that will negatively affect your clippy experience"
36 declare_clippy_lint! {
37 /// **What it does:** Ensures every lint is associated to a `LintPass`.
39 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
40 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
41 /// know the name of the lint.
43 /// **Known problems:** Only checks for lints associated using the
44 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
48 /// declare_lint! { pub LINT_1, ... }
49 /// declare_lint! { pub LINT_2, ... }
50 /// declare_lint! { pub FORGOTTEN_LINT, ... }
52 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
53 /// // missing FORGOTTEN_LINT
55 pub LINT_WITHOUT_LINT_PASS,
57 "declaring a lint without associating it in a LintPass"
60 declare_clippy_lint! {
61 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
62 /// variant of the function.
64 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
65 /// warning/error messages.
67 /// **Known problems:** None.
72 /// cx.span_lint(LINT_NAME, "message");
77 /// utils::span_lint(cx, LINT_NAME, "message");
79 pub COMPILER_LINT_FUNCTIONS,
81 "usage of the lint functions of the compiler instead of the utils::* variant"
84 declare_clippy_lint! {
85 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
86 /// the `cx.outer_expn_data()`
88 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
90 /// **Known problems:** None.
95 /// expr.span.ctxt().outer().expn_data()
100 /// expr.span.ctxt().outer_expn_data()
102 pub OUTER_EXPN_EXPN_DATA,
104 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
107 declare_clippy_lint! {
108 /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
109 /// error message by calling `panic`.
111 /// **Why is this bad?** ICE in large quantities can damage your teeth
113 /// **Known problems:** None
122 "this message should not appear anywhere as we ICE before and don't emit the lint"
125 declare_clippy_lint! {
126 /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
127 /// i.e. `default lint description`.
129 /// **Why is this bad?** Indicates that the lint is not finished.
131 /// **Known problems:** None
136 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
141 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
145 "found 'default lint description' in a lint declaration"
148 declare_clippy_lint! {
149 /// **What it does:** Lints `span_lint_and_then` function calls, where the
150 /// closure argument has only one statement and that statement is a method
151 /// call to `span_suggestion`, `span_help`, `span_note` (using the same
152 /// span), `help` or `note`.
154 /// These usages of `span_lint_and_then` should be replaced with one of the
155 /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
156 /// `span_lint_and_note`.
158 /// **Why is this bad?** Using the wrapper `span_lint_and_*` functions, is more
159 /// convenient, readable and less error prone.
161 /// **Known problems:** None
166 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
167 /// diag.span_suggestion(
170 /// sugg.to_string(),
171 /// Applicability::MachineApplicable,
174 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
175 /// diag.span_help(expr.span, help_msg);
177 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
178 /// diag.help(help_msg);
180 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
181 /// diag.span_note(expr.span, note_msg);
183 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
184 /// diag.note(note_msg);
190 /// span_lint_and_sugg(
196 /// sugg.to_string(),
197 /// Applicability::MachineApplicable,
199 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
200 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
201 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
202 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
204 pub COLLAPSIBLE_SPAN_LINT_CALLS,
206 "found collapsible `span_lint_and_then` calls"
209 declare_clippy_lint! {
210 /// **What it does:** Checks for calls to `utils::match_type()` on a type diagnostic item
211 /// and suggests to use `utils::is_type_diagnostic_item()` instead.
213 /// **Why is this bad?** `utils::is_type_diagnostic_item()` does not require hardcoded paths.
215 /// **Known problems:** None.
220 /// utils::match_type(cx, ty, &paths::VEC)
225 /// utils::is_type_diagnostic_item(cx, ty, sym!(vec_type))
227 pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
229 "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
232 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
234 impl EarlyLintPass for ClippyLintsInternal {
235 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
236 if let Some(utils) = krate
240 .find(|item| item.ident.name.as_str() == "utils")
242 if let ItemKind::Mod(ref utils_mod) = utils.kind {
243 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
244 if let ItemKind::Mod(ref paths_mod) = paths.kind {
245 let mut last_name: Option<SymbolStr> = None;
246 for item in &*paths_mod.items {
247 let name = item.ident.as_str();
248 if let Some(ref last_name) = last_name {
249 if **last_name > *name {
252 CLIPPY_LINTS_INTERNAL,
254 "this constant should be before the previous constant due to lexical \
259 last_name = Some(name);
268 #[derive(Clone, Debug, Default)]
269 pub struct LintWithoutLintPass {
270 declared_lints: FxHashMap<Symbol, Span>,
271 registered_lints: FxHashSet<Symbol>,
274 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
276 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
277 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
278 if !run_lints(cx, &[DEFAULT_LINT], item.hir_id) {
282 if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
283 if is_lint_ref_type(cx, ty) {
284 let expr = &cx.tcx.hir().body(body_id).value;
286 if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
287 if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
290 .find(|f| f.ident.as_str() == "desc")
291 .expect("lints must have a description field");
292 if let ExprKind::Lit(Spanned {
293 node: LitKind::Str(ref sym, _),
295 }) = field.expr.kind;
296 if sym.as_str() == "default lint description";
303 &format!("the lint `{}` has the default lint description", item.ident.name),
307 self.declared_lints.insert(item.ident.name, item.span);
309 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
310 || is_expn_of(item.span, "declare_lint_pass").is_some()
312 if let hir::ItemKind::Impl {
314 items: ref impl_item_refs,
318 let mut collector = LintCollector {
319 output: &mut self.registered_lints,
322 let body_id = cx.tcx.hir().body_owned_by(
325 .find(|iiref| iiref.ident.as_str() == "get_lints")
326 .expect("LintPass needs to implement get_lints")
330 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
335 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
336 if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
340 for (lint_name, &lint_span) in &self.declared_lints {
341 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
342 // file points to "<rustc macros>".
343 // `compiletest-rs` thinks that's an error in a different file and
344 // just ignores it. This causes the test in compile-fail/lint_pass
345 // not able to capture the error.
346 // Therefore, we need to climb the macro expansion tree and find the
347 // actual span that invoked `declare_tool_lint!`:
348 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
350 if !self.registered_lints.contains(lint_name) {
353 LINT_WITHOUT_LINT_PASS,
355 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
362 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
367 mutbl: Mutability::Not,
371 if let TyKind::Path(ref path) = inner.kind {
372 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
373 return match_def_path(cx, def_id, &paths::LINT);
381 struct LintCollector<'a, 'tcx> {
382 output: &'a mut FxHashSet<Symbol>,
383 cx: &'a LateContext<'tcx>,
386 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
387 type Map = Map<'tcx>;
389 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
390 if path.segments.len() == 1 {
391 self.output.insert(path.segments[0].ident.name);
395 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
396 NestedVisitorMap::All(self.cx.tcx.hir())
400 #[derive(Clone, Default)]
401 pub struct CompilerLintFunctions {
402 map: FxHashMap<&'static str, &'static str>,
405 impl CompilerLintFunctions {
407 pub fn new() -> Self {
408 let mut map = FxHashMap::default();
409 map.insert("span_lint", "utils::span_lint");
410 map.insert("struct_span_lint", "utils::span_lint");
411 map.insert("lint", "utils::span_lint");
412 map.insert("span_lint_note", "utils::span_lint_and_note");
413 map.insert("span_lint_help", "utils::span_lint_and_help");
418 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
420 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
421 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
422 if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
427 if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
428 let fn_name = path.ident;
429 if let Some(sugg) = self.map.get(&*fn_name.as_str());
430 let ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0]));
431 if match_type(cx, ty, &paths::EARLY_CONTEXT)
432 || match_type(cx, ty, &paths::LATE_CONTEXT);
436 COMPILER_LINT_FUNCTIONS,
438 "usage of a compiler lint function",
440 &format!("please use the Clippy variant of this function: `{}`", sugg),
447 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
449 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
450 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
451 if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
455 let (method_names, arg_lists, spans) = method_calls(expr, 2);
456 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
457 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
459 if let ["expn_data", "outer_expn"] = method_names.as_slice();
460 let args = arg_lists[1];
462 let self_arg = &args[0];
463 let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(self_arg));
464 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
468 OUTER_EXPN_EXPN_DATA,
469 spans[1].with_hi(expr.span.hi()),
470 "usage of `outer_expn().expn_data()`",
472 "outer_expn_data()".to_string(),
473 Applicability::MachineApplicable,
480 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
482 impl EarlyLintPass for ProduceIce {
483 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
484 if is_trigger_fn(fn_kind) {
485 panic!("Would you like some help with that?");
490 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
492 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
493 FnKind::Closure(..) => false,
497 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
499 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
500 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
501 if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
506 if let ExprKind::Call(ref func, ref and_then_args) = expr.kind;
507 if let ExprKind::Path(ref path) = func.kind;
508 if match_qpath(path, &["span_lint_and_then"]);
509 if and_then_args.len() == 5;
510 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
511 let body = cx.tcx.hir().body(*body_id);
512 if let ExprKind::Block(block, _) = &body.value.kind;
513 let stmts = &block.stmts;
514 if stmts.len() == 1 && block.expr.is_none();
515 if let StmtKind::Semi(only_expr) = &stmts[0].kind;
516 if let ExprKind::MethodCall(ref ps, _, ref span_call_args, _) = &only_expr.kind;
517 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
518 let mut sle = SpanlessEq::new(cx).deny_side_effects();
520 match &*ps.ident.as_str() {
521 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
522 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
524 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
525 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
526 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
528 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
529 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
530 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
533 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
534 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
537 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
538 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
547 struct AndThenSnippets<'a> {
554 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
555 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
556 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
557 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
558 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
568 struct SpanSuggestionSnippets<'a> {
571 applicability: Cow<'a, str>,
574 fn span_suggestion_snippets<'a, 'hir>(
575 cx: &LateContext<'_>,
576 span_call_args: &'hir [Expr<'hir>],
577 ) -> SpanSuggestionSnippets<'a> {
578 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
579 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
580 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
582 SpanSuggestionSnippets {
585 applicability: applicability_snippet,
589 fn suggest_suggestion(
590 cx: &LateContext<'_>,
592 and_then_snippets: &AndThenSnippets<'_>,
593 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
597 COLLAPSIBLE_SPAN_LINT_CALLS,
599 "this call is collapsible",
602 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
603 and_then_snippets.cx,
604 and_then_snippets.lint,
605 and_then_snippets.span,
606 and_then_snippets.msg,
607 span_suggestion_snippets.help,
608 span_suggestion_snippets.sugg,
609 span_suggestion_snippets.applicability
611 Applicability::MachineApplicable,
616 cx: &LateContext<'_>,
618 and_then_snippets: &AndThenSnippets<'_>,
622 let option_span = if with_span {
623 format!("Some({})", and_then_snippets.span)
630 COLLAPSIBLE_SPAN_LINT_CALLS,
632 "this call is collapsible",
635 "span_lint_and_help({}, {}, {}, {}, {}, {})",
636 and_then_snippets.cx,
637 and_then_snippets.lint,
638 and_then_snippets.span,
639 and_then_snippets.msg,
643 Applicability::MachineApplicable,
648 cx: &LateContext<'_>,
650 and_then_snippets: &AndThenSnippets<'_>,
654 let note_span = if with_span {
655 format!("Some({})", and_then_snippets.span)
662 COLLAPSIBLE_SPAN_LINT_CALLS,
664 "this call is collspible",
667 "span_lint_and_note({}, {}, {}, {}, {}, {})",
668 and_then_snippets.cx,
669 and_then_snippets.lint,
670 and_then_snippets.span,
671 and_then_snippets.msg,
675 Applicability::MachineApplicable,
679 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
681 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
682 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
683 if !run_lints(cx, &[MATCH_TYPE_ON_DIAGNOSTIC_ITEM], expr.hir_id) {
688 // Check if this is a call to utils::match_type()
689 if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
690 if let ExprKind::Path(fn_qpath) = &fn_path.kind;
691 if match_qpath(&fn_qpath, &["utils", "match_type"]);
692 // Extract the path to the matched type
693 if let Some(segments) = path_to_matched_type(cx, ty_path);
694 let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
695 if let Some(ty_did) = path_to_res(cx, &segments[..]).and_then(|res| res.opt_def_id());
696 // Check if the matched type is a diagnostic item
697 let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
698 if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
700 let cx_snippet = snippet(cx, context.span, "_");
701 let ty_snippet = snippet(cx, ty.span, "_");
705 MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
707 "usage of `utils::match_type()` on a type diagnostic item",
709 format!("utils::is_type_diagnostic_item({}, {}, sym!({}))", cx_snippet, ty_snippet, item_name),
710 Applicability::MaybeIncorrect,
717 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
718 use rustc_hir::ItemKind;
721 ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
722 ExprKind::Path(qpath) => match qpath_res(cx, qpath, expr.hir_id) {
723 Res::Local(hir_id) => {
724 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
725 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
726 if let Some(init) = local.init {
727 return path_to_matched_type(cx, init);
731 Res::Def(DefKind::Const | DefKind::Static, def_id) => {
732 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
733 if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
734 let body = cx.tcx.hir().body(body_id);
735 return path_to_matched_type(cx, &body.value);
741 ExprKind::Array(exprs) => {
742 let segments: Vec<SymbolStr> = exprs
745 if let ExprKind::Lit(lit) = &expr.kind {
746 if let LitKind::Str(sym, _) = lit.node {
747 return Some(sym.as_str());
755 if segments.len() == exprs.len() {
756 return Some(segments);