2 is_expn_of, match_def_path, match_qpath, match_type, method_calls, paths, run_lints, snippet, span_lint,
3 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, 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_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
211 impl EarlyLintPass for ClippyLintsInternal {
212 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
213 if let Some(utils) = krate
217 .find(|item| item.ident.name.as_str() == "utils")
219 if let ItemKind::Mod(ref utils_mod) = utils.kind {
220 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
221 if let ItemKind::Mod(ref paths_mod) = paths.kind {
222 let mut last_name: Option<SymbolStr> = None;
223 for item in &*paths_mod.items {
224 let name = item.ident.as_str();
225 if let Some(ref last_name) = last_name {
226 if **last_name > *name {
229 CLIPPY_LINTS_INTERNAL,
231 "this constant should be before the previous constant due to lexical \
236 last_name = Some(name);
245 #[derive(Clone, Debug, Default)]
246 pub struct LintWithoutLintPass {
247 declared_lints: FxHashMap<Symbol, Span>,
248 registered_lints: FxHashSet<Symbol>,
251 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
253 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
254 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
255 if !run_lints(cx, &[DEFAULT_LINT], item.hir_id) {
259 if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
260 if is_lint_ref_type(cx, ty) {
261 let expr = &cx.tcx.hir().body(body_id).value;
263 if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
264 if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
267 .find(|f| f.ident.as_str() == "desc")
268 .expect("lints must have a description field");
269 if let ExprKind::Lit(Spanned {
270 node: LitKind::Str(ref sym, _),
272 }) = field.expr.kind;
273 if sym.as_str() == "default lint description";
280 &format!("the lint `{}` has the default lint description", item.ident.name),
284 self.declared_lints.insert(item.ident.name, item.span);
286 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
287 || is_expn_of(item.span, "declare_lint_pass").is_some()
289 if let hir::ItemKind::Impl {
291 items: ref impl_item_refs,
295 let mut collector = LintCollector {
296 output: &mut self.registered_lints,
299 let body_id = cx.tcx.hir().body_owned_by(
302 .find(|iiref| iiref.ident.as_str() == "get_lints")
303 .expect("LintPass needs to implement get_lints")
307 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
312 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
313 if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
317 for (lint_name, &lint_span) in &self.declared_lints {
318 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
319 // file points to "<rustc macros>".
320 // `compiletest-rs` thinks that's an error in a different file and
321 // just ignores it. This causes the test in compile-fail/lint_pass
322 // not able to capture the error.
323 // Therefore, we need to climb the macro expansion tree and find the
324 // actual span that invoked `declare_tool_lint!`:
325 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
327 if !self.registered_lints.contains(lint_name) {
330 LINT_WITHOUT_LINT_PASS,
332 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
339 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
344 mutbl: Mutability::Not,
348 if let TyKind::Path(ref path) = inner.kind {
349 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
350 return match_def_path(cx, def_id, &paths::LINT);
358 struct LintCollector<'a, 'tcx> {
359 output: &'a mut FxHashSet<Symbol>,
360 cx: &'a LateContext<'tcx>,
363 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
364 type Map = Map<'tcx>;
366 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
367 if path.segments.len() == 1 {
368 self.output.insert(path.segments[0].ident.name);
372 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
373 NestedVisitorMap::All(self.cx.tcx.hir())
377 #[derive(Clone, Default)]
378 pub struct CompilerLintFunctions {
379 map: FxHashMap<&'static str, &'static str>,
382 impl CompilerLintFunctions {
384 pub fn new() -> Self {
385 let mut map = FxHashMap::default();
386 map.insert("span_lint", "utils::span_lint");
387 map.insert("struct_span_lint", "utils::span_lint");
388 map.insert("lint", "utils::span_lint");
389 map.insert("span_lint_note", "utils::span_lint_and_note");
390 map.insert("span_lint_help", "utils::span_lint_and_help");
395 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
397 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
398 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
399 if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
404 if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
405 let fn_name = path.ident;
406 if let Some(sugg) = self.map.get(&*fn_name.as_str());
407 let ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0]));
408 if match_type(cx, ty, &paths::EARLY_CONTEXT)
409 || match_type(cx, ty, &paths::LATE_CONTEXT);
413 COMPILER_LINT_FUNCTIONS,
415 "usage of a compiler lint function",
417 &format!("please use the Clippy variant of this function: `{}`", sugg),
424 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
426 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
427 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
428 if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
432 let (method_names, arg_lists, spans) = method_calls(expr, 2);
433 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
434 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
436 if let ["expn_data", "outer_expn"] = method_names.as_slice();
437 let args = arg_lists[1];
439 let self_arg = &args[0];
440 let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(self_arg));
441 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
445 OUTER_EXPN_EXPN_DATA,
446 spans[1].with_hi(expr.span.hi()),
447 "usage of `outer_expn().expn_data()`",
449 "outer_expn_data()".to_string(),
450 Applicability::MachineApplicable,
457 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
459 impl EarlyLintPass for ProduceIce {
460 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
461 if is_trigger_fn(fn_kind) {
462 panic!("Would you like some help with that?");
467 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
469 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
470 FnKind::Closure(..) => false,
474 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
476 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
477 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
478 if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
483 if let ExprKind::Call(ref func, ref and_then_args) = expr.kind;
484 if let ExprKind::Path(ref path) = func.kind;
485 if match_qpath(path, &["span_lint_and_then"]);
486 if and_then_args.len() == 5;
487 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
488 let body = cx.tcx.hir().body(*body_id);
489 if let ExprKind::Block(block, _) = &body.value.kind;
490 let stmts = &block.stmts;
491 if stmts.len() == 1 && block.expr.is_none();
492 if let StmtKind::Semi(only_expr) = &stmts[0].kind;
493 if let ExprKind::MethodCall(ref ps, _, ref span_call_args, _) = &only_expr.kind;
494 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
495 let mut sle = SpanlessEq::new(cx).deny_side_effects();
497 match &*ps.ident.as_str() {
498 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
499 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
501 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
502 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
503 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
505 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
506 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
507 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
510 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
511 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
514 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
515 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
524 struct AndThenSnippets<'a> {
531 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
532 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
533 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
534 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
535 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
545 struct SpanSuggestionSnippets<'a> {
548 applicability: Cow<'a, str>,
551 fn span_suggestion_snippets<'a, 'hir>(
552 cx: &LateContext<'_>,
553 span_call_args: &'hir [Expr<'hir>],
554 ) -> SpanSuggestionSnippets<'a> {
555 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
556 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
557 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
559 SpanSuggestionSnippets {
562 applicability: applicability_snippet,
566 fn suggest_suggestion(
567 cx: &LateContext<'_>,
569 and_then_snippets: &AndThenSnippets<'_>,
570 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
574 COLLAPSIBLE_SPAN_LINT_CALLS,
576 "this call is collapsible",
579 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
580 and_then_snippets.cx,
581 and_then_snippets.lint,
582 and_then_snippets.span,
583 and_then_snippets.msg,
584 span_suggestion_snippets.help,
585 span_suggestion_snippets.sugg,
586 span_suggestion_snippets.applicability
588 Applicability::MachineApplicable,
593 cx: &LateContext<'_>,
595 and_then_snippets: &AndThenSnippets<'_>,
599 let option_span = if with_span {
600 format!("Some({})", and_then_snippets.span)
607 COLLAPSIBLE_SPAN_LINT_CALLS,
609 "this call is collapsible",
612 "span_lint_and_help({}, {}, {}, {}, {}, {})",
613 and_then_snippets.cx,
614 and_then_snippets.lint,
615 and_then_snippets.span,
616 and_then_snippets.msg,
620 Applicability::MachineApplicable,
625 cx: &LateContext<'_>,
627 and_then_snippets: &AndThenSnippets<'_>,
631 let note_span = if with_span {
632 format!("Some({})", and_then_snippets.span)
639 COLLAPSIBLE_SPAN_LINT_CALLS,
641 "this call is collspible",
644 "span_lint_and_note({}, {}, {}, {}, {}, {})",
645 and_then_snippets.cx,
646 and_then_snippets.lint,
647 and_then_snippets.span,
648 and_then_snippets.msg,
652 Applicability::MachineApplicable,