]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
Merge commit 'e636b88aa180e8cab9e28802aac90adbc984234d' into clippyup
[rust.git] / clippy_lints / src / utils / internal_lints.rs
1 use crate::utils::{
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, SpanlessEq,
4 };
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;
10 use rustc_hir as hir;
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};
20
21 use std::borrow::{Borrow, Cow};
22
23 declare_clippy_lint! {
24     /// **What it does:** Checks for various things we like to keep tidy in clippy.
25     ///
26     /// **Why is this bad?** We like to pretend we're an example of tidy code.
27     ///
28     /// **Known problems:** None.
29     ///
30     /// **Example:** Wrong ordering of the util::paths constants.
31     pub CLIPPY_LINTS_INTERNAL,
32     internal,
33     "various things that will negatively affect your clippy experience"
34 }
35
36 declare_clippy_lint! {
37     /// **What it does:** Ensures every lint is associated to a `LintPass`.
38     ///
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.
42     ///
43     /// **Known problems:** Only checks for lints associated using the
44     /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
45     ///
46     /// **Example:**
47     /// ```rust,ignore
48     /// declare_lint! { pub LINT_1, ... }
49     /// declare_lint! { pub LINT_2, ... }
50     /// declare_lint! { pub FORGOTTEN_LINT, ... }
51     /// // ...
52     /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
53     /// // missing FORGOTTEN_LINT
54     /// ```
55     pub LINT_WITHOUT_LINT_PASS,
56     internal,
57     "declaring a lint without associating it in a LintPass"
58 }
59
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.
63     ///
64     /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
65     /// warning/error messages.
66     ///
67     /// **Known problems:** None.
68     ///
69     /// **Example:**
70     /// Bad:
71     /// ```rust,ignore
72     /// cx.span_lint(LINT_NAME, "message");
73     /// ```
74     ///
75     /// Good:
76     /// ```rust,ignore
77     /// utils::span_lint(cx, LINT_NAME, "message");
78     /// ```
79     pub COMPILER_LINT_FUNCTIONS,
80     internal,
81     "usage of the lint functions of the compiler instead of the utils::* variant"
82 }
83
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()`
87     ///
88     /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
89     ///
90     /// **Known problems:** None.
91     ///
92     /// **Example:**
93     /// Bad:
94     /// ```rust,ignore
95     /// expr.span.ctxt().outer().expn_data()
96     /// ```
97     ///
98     /// Good:
99     /// ```rust,ignore
100     /// expr.span.ctxt().outer_expn_data()
101     /// ```
102     pub OUTER_EXPN_EXPN_DATA,
103     internal,
104     "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
105 }
106
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`.
110     ///
111     /// **Why is this bad?** ICE in large quantities can damage your teeth
112     ///
113     /// **Known problems:** None
114     ///
115     /// **Example:**
116     /// Bad:
117     /// ```rust,ignore
118     /// 🍦🍦🍦🍦🍦
119     /// ```
120     pub PRODUCE_ICE,
121     internal,
122     "this message should not appear anywhere as we ICE before and don't emit the lint"
123 }
124
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`.
128     ///
129     /// **Why is this bad?** Indicates that the lint is not finished.
130     ///
131     /// **Known problems:** None
132     ///
133     /// **Example:**
134     /// Bad:
135     /// ```rust,ignore
136     /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
137     /// ```
138     ///
139     /// Good:
140     /// ```rust,ignore
141     /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
142     /// ```
143     pub DEFAULT_LINT,
144     internal,
145     "found 'default lint description' in a lint declaration"
146 }
147
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`.
153     ///
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`.
157     ///
158     /// **Why is this bad?** Using the wrapper `span_lint_and_*` functions, is more
159     /// convenient, readable and less error prone.
160     ///
161     /// **Known problems:** None
162     ///
163     /// *Example:**
164     /// Bad:
165     /// ```rust,ignore
166     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
167     ///     diag.span_suggestion(
168     ///         expr.span,
169     ///         help_msg,
170     ///         sugg.to_string(),
171     ///         Applicability::MachineApplicable,
172     ///     );
173     /// });
174     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
175     ///     diag.span_help(expr.span, help_msg);
176     /// });
177     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
178     ///     diag.help(help_msg);
179     /// });
180     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
181     ///     diag.span_note(expr.span, note_msg);
182     /// });
183     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
184     ///     diag.note(note_msg);
185     /// });
186     /// ```
187     ///
188     /// Good:
189     /// ```rust,ignore
190     /// span_lint_and_sugg(
191     ///     cx,
192     ///     TEST_LINT,
193     ///     expr.span,
194     ///     lint_msg,
195     ///     help_msg,
196     ///     sugg.to_string(),
197     ///     Applicability::MachineApplicable,
198     /// );
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);
203     /// ```
204     pub COLLAPSIBLE_SPAN_LINT_CALLS,
205     internal,
206     "found collapsible `span_lint_and_then` calls"
207 }
208
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.
212     ///
213     /// **Why is this bad?** `utils::is_type_diagnostic_item()` does not require hardcoded paths.
214     ///
215     /// **Known problems:** None.
216     ///
217     /// **Example:**
218     /// Bad:
219     /// ```rust,ignore
220     /// utils::match_type(cx, ty, &paths::VEC)
221     /// ```
222     ///
223     /// Good:
224     /// ```rust,ignore
225     /// utils::is_type_diagnostic_item(cx, ty, sym!(vec_type))
226     /// ```
227     pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
228     internal,
229     "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
230 }
231
232 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
233
234 impl EarlyLintPass for ClippyLintsInternal {
235     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
236         if let Some(utils) = krate
237             .module
238             .items
239             .iter()
240             .find(|item| item.ident.name.as_str() == "utils")
241         {
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 {
250                                     span_lint(
251                                         cx,
252                                         CLIPPY_LINTS_INTERNAL,
253                                         item.span,
254                                         "this constant should be before the previous constant due to lexical \
255                                          ordering",
256                                     );
257                                 }
258                             }
259                             last_name = Some(name);
260                         }
261                     }
262                 }
263             }
264         }
265     }
266 }
267
268 #[derive(Clone, Debug, Default)]
269 pub struct LintWithoutLintPass {
270     declared_lints: FxHashMap<Symbol, Span>,
271     registered_lints: FxHashSet<Symbol>,
272 }
273
274 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
275
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) {
279             return;
280         }
281
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;
285                 if_chain! {
286                     if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
287                     if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
288                     let field = fields
289                         .iter()
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, _),
294                         ..
295                     }) = field.expr.kind;
296                     if sym.as_str() == "default lint description";
297
298                     then {
299                         span_lint(
300                             cx,
301                             DEFAULT_LINT,
302                             item.span,
303                             &format!("the lint `{}` has the default lint description", item.ident.name),
304                         );
305                     }
306                 }
307                 self.declared_lints.insert(item.ident.name, item.span);
308             }
309         } else if is_expn_of(item.span, "impl_lint_pass").is_some()
310             || is_expn_of(item.span, "declare_lint_pass").is_some()
311         {
312             if let hir::ItemKind::Impl {
313                 of_trait: None,
314                 items: ref impl_item_refs,
315                 ..
316             } = item.kind
317             {
318                 let mut collector = LintCollector {
319                     output: &mut self.registered_lints,
320                     cx,
321                 };
322                 let body_id = cx.tcx.hir().body_owned_by(
323                     impl_item_refs
324                         .iter()
325                         .find(|iiref| iiref.ident.as_str() == "get_lints")
326                         .expect("LintPass needs to implement get_lints")
327                         .id
328                         .hir_id,
329                 );
330                 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
331             }
332         }
333     }
334
335     fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
336         if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
337             return;
338         }
339
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;
349
350             if !self.registered_lints.contains(lint_name) {
351                 span_lint(
352                     cx,
353                     LINT_WITHOUT_LINT_PASS,
354                     lint_span,
355                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
356                 );
357             }
358         }
359     }
360 }
361
362 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
363     if let TyKind::Rptr(
364         _,
365         MutTy {
366             ty: ref inner,
367             mutbl: Mutability::Not,
368         },
369     ) = ty.kind
370     {
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);
374             }
375         }
376     }
377
378     false
379 }
380
381 struct LintCollector<'a, 'tcx> {
382     output: &'a mut FxHashSet<Symbol>,
383     cx: &'a LateContext<'tcx>,
384 }
385
386 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
387     type Map = Map<'tcx>;
388
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);
392         }
393     }
394
395     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
396         NestedVisitorMap::All(self.cx.tcx.hir())
397     }
398 }
399
400 #[derive(Clone, Default)]
401 pub struct CompilerLintFunctions {
402     map: FxHashMap<&'static str, &'static str>,
403 }
404
405 impl CompilerLintFunctions {
406     #[must_use]
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");
414         Self { map }
415     }
416 }
417
418 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
419
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) {
423             return;
424         }
425
426         if_chain! {
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 = cx.typeck_results().expr_ty(&args[0]).peel_refs();
431             if match_type(cx, ty, &paths::EARLY_CONTEXT)
432                 || match_type(cx, ty, &paths::LATE_CONTEXT);
433             then {
434                 span_lint_and_help(
435                     cx,
436                     COMPILER_LINT_FUNCTIONS,
437                     path.ident.span,
438                     "usage of a compiler lint function",
439                     None,
440                     &format!("please use the Clippy variant of this function: `{}`", sugg),
441                 );
442             }
443         }
444     }
445 }
446
447 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
448
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) {
452             return;
453         }
454
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();
458         if_chain! {
459             if let ["expn_data", "outer_expn"] = method_names.as_slice();
460             let args = arg_lists[1];
461             if args.len() == 1;
462             let self_arg = &args[0];
463             let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
464             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
465             then {
466                 span_lint_and_sugg(
467                     cx,
468                     OUTER_EXPN_EXPN_DATA,
469                     spans[1].with_hi(expr.span.hi()),
470                     "usage of `outer_expn().expn_data()`",
471                     "try",
472                     "outer_expn_data()".to_string(),
473                     Applicability::MachineApplicable,
474                 );
475             }
476         }
477     }
478 }
479
480 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
481
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?");
486         }
487     }
488 }
489
490 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
491     match fn_kind {
492         FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
493         FnKind::Closure(..) => false,
494     }
495 }
496
497 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
498
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) {
502             return;
503         }
504
505         if_chain! {
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();
519             then {
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));
523                     },
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);
527                     },
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);
531                     },
532                     "help" => {
533                         let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
534                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
535                     }
536                     "note" => {
537                         let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
538                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
539                     }
540                     _  => (),
541                 }
542             }
543         }
544     }
545 }
546
547 struct AndThenSnippets<'a> {
548     cx: Cow<'a, str>,
549     lint: Cow<'a, str>,
550     span: Cow<'a, str>,
551     msg: Cow<'a, str>,
552 }
553
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#""...""#);
559
560     AndThenSnippets {
561         cx: cx_snippet,
562         lint: lint_snippet,
563         span: span_snippet,
564         msg: msg_snippet,
565     }
566 }
567
568 struct SpanSuggestionSnippets<'a> {
569     help: Cow<'a, str>,
570     sugg: Cow<'a, str>,
571     applicability: Cow<'a, str>,
572 }
573
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");
581
582     SpanSuggestionSnippets {
583         help: help_snippet,
584         sugg: sugg_snippet,
585         applicability: applicability_snippet,
586     }
587 }
588
589 fn suggest_suggestion(
590     cx: &LateContext<'_>,
591     expr: &Expr<'_>,
592     and_then_snippets: &AndThenSnippets<'_>,
593     span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
594 ) {
595     span_lint_and_sugg(
596         cx,
597         COLLAPSIBLE_SPAN_LINT_CALLS,
598         expr.span,
599         "this call is collapsible",
600         "collapse into",
601         format!(
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
610         ),
611         Applicability::MachineApplicable,
612     );
613 }
614
615 fn suggest_help(
616     cx: &LateContext<'_>,
617     expr: &Expr<'_>,
618     and_then_snippets: &AndThenSnippets<'_>,
619     help: &str,
620     with_span: bool,
621 ) {
622     let option_span = if with_span {
623         format!("Some({})", and_then_snippets.span)
624     } else {
625         "None".to_string()
626     };
627
628     span_lint_and_sugg(
629         cx,
630         COLLAPSIBLE_SPAN_LINT_CALLS,
631         expr.span,
632         "this call is collapsible",
633         "collapse into",
634         format!(
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,
640             &option_span,
641             help
642         ),
643         Applicability::MachineApplicable,
644     );
645 }
646
647 fn suggest_note(
648     cx: &LateContext<'_>,
649     expr: &Expr<'_>,
650     and_then_snippets: &AndThenSnippets<'_>,
651     note: &str,
652     with_span: bool,
653 ) {
654     let note_span = if with_span {
655         format!("Some({})", and_then_snippets.span)
656     } else {
657         "None".to_string()
658     };
659
660     span_lint_and_sugg(
661         cx,
662         COLLAPSIBLE_SPAN_LINT_CALLS,
663         expr.span,
664         "this call is collspible",
665         "collapse into",
666         format!(
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,
672             note_span,
673             note
674         ),
675         Applicability::MachineApplicable,
676     );
677 }
678
679 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
680
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) {
684             return;
685         }
686
687         if_chain! {
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 });
699             then {
700                 let cx_snippet = snippet(cx, context.span, "_");
701                 let ty_snippet = snippet(cx, ty.span, "_");
702
703                 span_lint_and_sugg(
704                     cx,
705                     MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
706                     expr.span,
707                     "usage of `utils::match_type()` on a type diagnostic item",
708                     "try",
709                     format!("utils::is_type_diagnostic_item({}, {}, sym!({}))", cx_snippet, ty_snippet, item_name),
710                     Applicability::MaybeIncorrect,
711                 );
712             }
713         }
714     }
715 }
716
717 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
718     use rustc_hir::ItemKind;
719
720     match &expr.kind {
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);
728                     }
729                 }
730             },
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);
736                     }
737                 }
738             },
739             _ => {},
740         },
741         ExprKind::Array(exprs) => {
742             let segments: Vec<SymbolStr> = exprs
743                 .iter()
744                 .filter_map(|expr| {
745                     if let ExprKind::Lit(lit) = &expr.kind {
746                         if let LitKind::Str(sym, _) = lit.node {
747                             return Some(sym.as_str());
748                         }
749                     }
750
751                     None
752                 })
753                 .collect();
754
755             if segments.len() == exprs.len() {
756                 return Some(segments);
757             }
758         },
759         _ => {},
760     }
761
762     None
763 }