]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/dbg_macro.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / dbg_macro.rs
1 use crate::utils::{snippet_opt, span_help_and_lint, span_lint_and_sugg};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use rustc_errors::Applicability;
5 use syntax::ast;
6 use syntax::source_map::Span;
7 use syntax::tokenstream::TokenStream;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for usage of dbg!() macro.
11     ///
12     /// **Why is this bad?** `dbg!` macro is intended as a debugging tool. It
13     /// should not be in version control.
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust,ignore
19     /// // Bad
20     /// dbg!(true)
21     ///
22     /// // Good
23     /// true
24     /// ```
25     pub DBG_MACRO,
26     restriction,
27     "`dbg!` macro is intended as a debugging tool"
28 }
29
30 #[derive(Copy, Clone, Debug)]
31 pub struct Pass;
32
33 impl LintPass for Pass {
34     fn get_lints(&self) -> LintArray {
35         lint_array!(DBG_MACRO)
36     }
37
38     fn name(&self) -> &'static str {
39         "DbgMacro"
40     }
41 }
42
43 impl EarlyLintPass for Pass {
44     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
45         if mac.node.path == "dbg" {
46             if let Some(sugg) = tts_span(mac.node.tts.clone()).and_then(|span| snippet_opt(cx, span)) {
47                 span_lint_and_sugg(
48                     cx,
49                     DBG_MACRO,
50                     mac.span,
51                     "`dbg!` macro is intended as a debugging tool",
52                     "ensure to avoid having uses of it in version control",
53                     sugg,
54                     Applicability::MaybeIncorrect,
55                 );
56             } else {
57                 span_help_and_lint(
58                     cx,
59                     DBG_MACRO,
60                     mac.span,
61                     "`dbg!` macro is intended as a debugging tool",
62                     "ensure to avoid having uses of it in version control",
63                 );
64             }
65         }
66     }
67 }
68
69 // Get span enclosing entire the token stream.
70 fn tts_span(tts: TokenStream) -> Option<Span> {
71     let mut cursor = tts.into_trees();
72     let first = cursor.next()?.span();
73     let span = match cursor.last() {
74         Some(tree) => first.to(tree.span()),
75         None => first,
76     };
77     Some(span)
78 }