]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/dbg_macro.rs
Auto merge of #7956 - camsteffen:author, r=llogiq
[rust.git] / clippy_lints / src / dbg_macro.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::source::snippet_opt;
3 use rustc_ast::ast;
4 use rustc_ast::tokenstream::TokenStream;
5 use rustc_errors::Applicability;
6 use rustc_lint::{EarlyContext, EarlyLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::source_map::Span;
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Checks for usage of dbg!() macro.
13     ///
14     /// ### Why is this bad?
15     /// `dbg!` macro is intended as a debugging tool. It
16     /// should not be in version control.
17     ///
18     /// ### Example
19     /// ```rust,ignore
20     /// // Bad
21     /// dbg!(true)
22     ///
23     /// // Good
24     /// true
25     /// ```
26     #[clippy::version = "1.34.0"]
27     pub DBG_MACRO,
28     restriction,
29     "`dbg!` macro is intended as a debugging tool"
30 }
31
32 declare_lint_pass!(DbgMacro => [DBG_MACRO]);
33
34 impl EarlyLintPass for DbgMacro {
35     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) {
36         if mac.path == sym!(dbg) {
37             if let Some(sugg) = tts_span(mac.args.inner_tokens()).and_then(|span| snippet_opt(cx, span)) {
38                 span_lint_and_sugg(
39                     cx,
40                     DBG_MACRO,
41                     mac.span(),
42                     "`dbg!` macro is intended as a debugging tool",
43                     "ensure to avoid having uses of it in version control",
44                     sugg,
45                     Applicability::MaybeIncorrect,
46                 );
47             } else {
48                 span_lint_and_help(
49                     cx,
50                     DBG_MACRO,
51                     mac.span(),
52                     "`dbg!` macro is intended as a debugging tool",
53                     None,
54                     "ensure to avoid having uses of it in version control",
55                 );
56             }
57         }
58     }
59 }
60
61 // Get span enclosing entire the token stream.
62 fn tts_span(tts: TokenStream) -> Option<Span> {
63     let mut cursor = tts.into_trees();
64     let first = cursor.next()?.span();
65     let span = cursor.last().map_or(first, |tree| first.to(tree.span()));
66     Some(span)
67 }