]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/dbg_macro.rs
use snippet for making a suggestion if possible
[rust.git] / clippy_lints / src / dbg_macro.rs
1 use crate::utils::{span_help_and_lint, span_lint_and_sugg, snippet_opt};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use syntax::ast;
5 use rustc_errors::Applicability;
6 use syntax::tokenstream::TokenStream;
7 use syntax::source_map::Span;
8
9 /// **What it does:** Checks for usage of dbg!() macro.
10 ///
11 /// **Why is this bad?** `dbg!` macro is intended as a debugging tool. It
12 /// should not be in version control.
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 /// ```rust,ignore
18 /// // Bad
19 /// dbg!(true)
20 ///
21 /// // Good
22 /// true
23 /// ```
24 declare_clippy_lint! {
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             match tts_span(mac.node.tts.clone()).and_then(|span| snippet_opt(cx, span)) {
47                 Some(sugg) => {
48                     span_lint_and_sugg(
49                         cx,
50                         DBG_MACRO,
51                         mac.span,
52                         "`dbg!` macro is intended as a debugging tool",
53                         "ensure to avoid having uses of it in version control",
54                         sugg,
55                         Applicability::MaybeIncorrect,
56                     );
57                 }
58                 None => {
59                     span_help_and_lint(
60                         cx,
61                         DBG_MACRO,
62                         mac.span,
63                         "`dbg!` macro is intended as a debugging tool",
64                         "ensure to avoid having uses of it in version control",
65                     );
66                 }
67             };
68         }
69     }
70 }
71
72 // Get span enclosing entire the token stream.
73 fn tts_span(tts: TokenStream) -> Option<Span> {
74     let mut cursor = tts.into_trees();
75     let first = cursor.next()?.span();
76     let span = match cursor.last() {
77         Some(tree) => first.to(tree.span()),
78         None => first,
79     };
80     Some(span)
81 }