]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/internal_lints.rs
Rollup merge of #81588 - xfix:delete-doc-alias, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / utils / internal_lints.rs
1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{
3     is_expn_of, match_def_path, match_qpath, match_type, method_calls, path_to_res, paths, run_lints, snippet,
4     span_lint, span_lint_and_help, span_lint_and_sugg, SpanlessEq,
5 };
6 use if_chain::if_chain;
7 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, NodeId};
8 use rustc_ast::visit::FnKind;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_errors::Applicability;
11 use rustc_hir as hir;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::DefId;
14 use rustc_hir::hir_id::CRATE_HIR_ID;
15 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
16 use rustc_hir::{
17     BinOpKind, Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Node, Path, StmtKind, Ty, TyKind, UnOp,
18 };
19 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::mir::interpret::ConstValue;
22 use rustc_middle::ty;
23 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
24 use rustc_span::source_map::{Span, Spanned};
25 use rustc_span::symbol::{Symbol, SymbolStr};
26 use rustc_typeck::hir_ty_to_ty;
27
28 use std::borrow::{Borrow, Cow};
29
30 declare_clippy_lint! {
31     /// **What it does:** Checks for various things we like to keep tidy in clippy.
32     ///
33     /// **Why is this bad?** We like to pretend we're an example of tidy code.
34     ///
35     /// **Known problems:** None.
36     ///
37     /// **Example:** Wrong ordering of the util::paths constants.
38     pub CLIPPY_LINTS_INTERNAL,
39     internal,
40     "various things that will negatively affect your clippy experience"
41 }
42
43 declare_clippy_lint! {
44     /// **What it does:** Ensures every lint is associated to a `LintPass`.
45     ///
46     /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
47     /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
48     /// know the name of the lint.
49     ///
50     /// **Known problems:** Only checks for lints associated using the
51     /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
52     ///
53     /// **Example:**
54     /// ```rust,ignore
55     /// declare_lint! { pub LINT_1, ... }
56     /// declare_lint! { pub LINT_2, ... }
57     /// declare_lint! { pub FORGOTTEN_LINT, ... }
58     /// // ...
59     /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
60     /// // missing FORGOTTEN_LINT
61     /// ```
62     pub LINT_WITHOUT_LINT_PASS,
63     internal,
64     "declaring a lint without associating it in a LintPass"
65 }
66
67 declare_clippy_lint! {
68     /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
69     /// variant of the function.
70     ///
71     /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
72     /// warning/error messages.
73     ///
74     /// **Known problems:** None.
75     ///
76     /// **Example:**
77     /// Bad:
78     /// ```rust,ignore
79     /// cx.span_lint(LINT_NAME, "message");
80     /// ```
81     ///
82     /// Good:
83     /// ```rust,ignore
84     /// utils::span_lint(cx, LINT_NAME, "message");
85     /// ```
86     pub COMPILER_LINT_FUNCTIONS,
87     internal,
88     "usage of the lint functions of the compiler instead of the utils::* variant"
89 }
90
91 declare_clippy_lint! {
92     /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
93     /// the `cx.outer_expn_data()`
94     ///
95     /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
96     ///
97     /// **Known problems:** None.
98     ///
99     /// **Example:**
100     /// Bad:
101     /// ```rust,ignore
102     /// expr.span.ctxt().outer().expn_data()
103     /// ```
104     ///
105     /// Good:
106     /// ```rust,ignore
107     /// expr.span.ctxt().outer_expn_data()
108     /// ```
109     pub OUTER_EXPN_EXPN_DATA,
110     internal,
111     "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
112 }
113
114 declare_clippy_lint! {
115     /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
116     /// error message by calling `panic`.
117     ///
118     /// **Why is this bad?** ICE in large quantities can damage your teeth
119     ///
120     /// **Known problems:** None
121     ///
122     /// **Example:**
123     /// Bad:
124     /// ```rust,ignore
125     /// 🍦🍦🍦🍦🍦
126     /// ```
127     pub PRODUCE_ICE,
128     internal,
129     "this message should not appear anywhere as we ICE before and don't emit the lint"
130 }
131
132 declare_clippy_lint! {
133     /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
134     /// i.e. `default lint description`.
135     ///
136     /// **Why is this bad?** Indicates that the lint is not finished.
137     ///
138     /// **Known problems:** None
139     ///
140     /// **Example:**
141     /// Bad:
142     /// ```rust,ignore
143     /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
144     /// ```
145     ///
146     /// Good:
147     /// ```rust,ignore
148     /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
149     /// ```
150     pub DEFAULT_LINT,
151     internal,
152     "found 'default lint description' in a lint declaration"
153 }
154
155 declare_clippy_lint! {
156     /// **What it does:** Lints `span_lint_and_then` function calls, where the
157     /// closure argument has only one statement and that statement is a method
158     /// call to `span_suggestion`, `span_help`, `span_note` (using the same
159     /// span), `help` or `note`.
160     ///
161     /// These usages of `span_lint_and_then` should be replaced with one of the
162     /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
163     /// `span_lint_and_note`.
164     ///
165     /// **Why is this bad?** Using the wrapper `span_lint_and_*` functions, is more
166     /// convenient, readable and less error prone.
167     ///
168     /// **Known problems:** None
169     ///
170     /// *Example:**
171     /// Bad:
172     /// ```rust,ignore
173     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
174     ///     diag.span_suggestion(
175     ///         expr.span,
176     ///         help_msg,
177     ///         sugg.to_string(),
178     ///         Applicability::MachineApplicable,
179     ///     );
180     /// });
181     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
182     ///     diag.span_help(expr.span, help_msg);
183     /// });
184     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
185     ///     diag.help(help_msg);
186     /// });
187     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
188     ///     diag.span_note(expr.span, note_msg);
189     /// });
190     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
191     ///     diag.note(note_msg);
192     /// });
193     /// ```
194     ///
195     /// Good:
196     /// ```rust,ignore
197     /// span_lint_and_sugg(
198     ///     cx,
199     ///     TEST_LINT,
200     ///     expr.span,
201     ///     lint_msg,
202     ///     help_msg,
203     ///     sugg.to_string(),
204     ///     Applicability::MachineApplicable,
205     /// );
206     /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
207     /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
208     /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
209     /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
210     /// ```
211     pub COLLAPSIBLE_SPAN_LINT_CALLS,
212     internal,
213     "found collapsible `span_lint_and_then` calls"
214 }
215
216 declare_clippy_lint! {
217     /// **What it does:** Checks for calls to `utils::match_type()` on a type diagnostic item
218     /// and suggests to use `utils::is_type_diagnostic_item()` instead.
219     ///
220     /// **Why is this bad?** `utils::is_type_diagnostic_item()` does not require hardcoded paths.
221     ///
222     /// **Known problems:** None.
223     ///
224     /// **Example:**
225     /// Bad:
226     /// ```rust,ignore
227     /// utils::match_type(cx, ty, &paths::VEC)
228     /// ```
229     ///
230     /// Good:
231     /// ```rust,ignore
232     /// utils::is_type_diagnostic_item(cx, ty, sym::vec_type)
233     /// ```
234     pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
235     internal,
236     "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
237 }
238
239 declare_clippy_lint! {
240     /// **What it does:**
241     /// Checks the paths module for invalid paths.
242     ///
243     /// **Why is this bad?**
244     /// It indicates a bug in the code.
245     ///
246     /// **Known problems:** None.
247     ///
248     /// **Example:** None.
249     pub INVALID_PATHS,
250     internal,
251     "invalid path"
252 }
253
254 declare_clippy_lint! {
255     /// **What it does:**
256     /// Checks for interning symbols that have already been pre-interned and defined as constants.
257     ///
258     /// **Why is this bad?**
259     /// It's faster and easier to use the symbol constant.
260     ///
261     /// **Known problems:** None.
262     ///
263     /// **Example:**
264     /// Bad:
265     /// ```rust,ignore
266     /// let _ = sym!(f32);
267     /// ```
268     ///
269     /// Good:
270     /// ```rust,ignore
271     /// let _ = sym::f32;
272     /// ```
273     pub INTERNING_DEFINED_SYMBOL,
274     internal,
275     "interning a symbol that is pre-interned and defined as a constant"
276 }
277
278 declare_clippy_lint! {
279     /// **What it does:** Checks for unnecessary conversion from Symbol to a string.
280     ///
281     /// **Why is this bad?** It's faster use symbols directly intead of strings.
282     ///
283     /// **Known problems:** None.
284     ///
285     /// **Example:**
286     /// Bad:
287     /// ```rust,ignore
288     /// symbol.as_str() == "clippy";
289     /// ```
290     ///
291     /// Good:
292     /// ```rust,ignore
293     /// symbol == sym::clippy;
294     /// ```
295     pub UNNECESSARY_SYMBOL_STR,
296     internal,
297     "unnecessary conversion between Symbol and string"
298 }
299
300 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
301
302 impl EarlyLintPass for ClippyLintsInternal {
303     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
304         if let Some(utils) = krate
305             .module
306             .items
307             .iter()
308             .find(|item| item.ident.name.as_str() == "utils")
309         {
310             if let ItemKind::Mod(ref utils_mod) = utils.kind {
311                 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
312                     if let ItemKind::Mod(ref paths_mod) = paths.kind {
313                         let mut last_name: Option<SymbolStr> = None;
314                         for item in &*paths_mod.items {
315                             let name = item.ident.as_str();
316                             if let Some(ref last_name) = last_name {
317                                 if **last_name > *name {
318                                     span_lint(
319                                         cx,
320                                         CLIPPY_LINTS_INTERNAL,
321                                         item.span,
322                                         "this constant should be before the previous constant due to lexical \
323                                          ordering",
324                                     );
325                                 }
326                             }
327                             last_name = Some(name);
328                         }
329                     }
330                 }
331             }
332         }
333     }
334 }
335
336 #[derive(Clone, Debug, Default)]
337 pub struct LintWithoutLintPass {
338     declared_lints: FxHashMap<Symbol, Span>,
339     registered_lints: FxHashSet<Symbol>,
340 }
341
342 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
343
344 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
345     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
346         if !run_lints(cx, &[DEFAULT_LINT], item.hir_id) {
347             return;
348         }
349
350         if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
351             if is_lint_ref_type(cx, ty) {
352                 let expr = &cx.tcx.hir().body(body_id).value;
353                 if_chain! {
354                     if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
355                     if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
356                     let field = fields
357                         .iter()
358                         .find(|f| f.ident.as_str() == "desc")
359                         .expect("lints must have a description field");
360                     if let ExprKind::Lit(Spanned {
361                         node: LitKind::Str(ref sym, _),
362                         ..
363                     }) = field.expr.kind;
364                     if sym.as_str() == "default lint description";
365
366                     then {
367                         span_lint(
368                             cx,
369                             DEFAULT_LINT,
370                             item.span,
371                             &format!("the lint `{}` has the default lint description", item.ident.name),
372                         );
373                     }
374                 }
375                 self.declared_lints.insert(item.ident.name, item.span);
376             }
377         } else if is_expn_of(item.span, "impl_lint_pass").is_some()
378             || is_expn_of(item.span, "declare_lint_pass").is_some()
379         {
380             if let hir::ItemKind::Impl(hir::Impl {
381                 of_trait: None,
382                 items: ref impl_item_refs,
383                 ..
384             }) = item.kind
385             {
386                 let mut collector = LintCollector {
387                     output: &mut self.registered_lints,
388                     cx,
389                 };
390                 let body_id = cx.tcx.hir().body_owned_by(
391                     impl_item_refs
392                         .iter()
393                         .find(|iiref| iiref.ident.as_str() == "get_lints")
394                         .expect("LintPass needs to implement get_lints")
395                         .id
396                         .hir_id,
397                 );
398                 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
399             }
400         }
401     }
402
403     fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
404         if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
405             return;
406         }
407
408         for (lint_name, &lint_span) in &self.declared_lints {
409             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
410             // file points to "<rustc macros>".
411             // `compiletest-rs` thinks that's an error in a different file and
412             // just ignores it. This causes the test in compile-fail/lint_pass
413             // not able to capture the error.
414             // Therefore, we need to climb the macro expansion tree and find the
415             // actual span that invoked `declare_tool_lint!`:
416             let lint_span = lint_span.ctxt().outer_expn_data().call_site;
417
418             if !self.registered_lints.contains(lint_name) {
419                 span_lint(
420                     cx,
421                     LINT_WITHOUT_LINT_PASS,
422                     lint_span,
423                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
424                 );
425             }
426         }
427     }
428 }
429
430 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
431     if let TyKind::Rptr(
432         _,
433         MutTy {
434             ty: ref inner,
435             mutbl: Mutability::Not,
436         },
437     ) = ty.kind
438     {
439         if let TyKind::Path(ref path) = inner.kind {
440             if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
441                 return match_def_path(cx, def_id, &paths::LINT);
442             }
443         }
444     }
445
446     false
447 }
448
449 struct LintCollector<'a, 'tcx> {
450     output: &'a mut FxHashSet<Symbol>,
451     cx: &'a LateContext<'tcx>,
452 }
453
454 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
455     type Map = Map<'tcx>;
456
457     fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
458         if path.segments.len() == 1 {
459             self.output.insert(path.segments[0].ident.name);
460         }
461     }
462
463     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
464         NestedVisitorMap::All(self.cx.tcx.hir())
465     }
466 }
467
468 #[derive(Clone, Default)]
469 pub struct CompilerLintFunctions {
470     map: FxHashMap<&'static str, &'static str>,
471 }
472
473 impl CompilerLintFunctions {
474     #[must_use]
475     pub fn new() -> Self {
476         let mut map = FxHashMap::default();
477         map.insert("span_lint", "utils::span_lint");
478         map.insert("struct_span_lint", "utils::span_lint");
479         map.insert("lint", "utils::span_lint");
480         map.insert("span_lint_note", "utils::span_lint_and_note");
481         map.insert("span_lint_help", "utils::span_lint_and_help");
482         Self { map }
483     }
484 }
485
486 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
487
488 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
489     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
490         if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
491             return;
492         }
493
494         if_chain! {
495             if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
496             let fn_name = path.ident;
497             if let Some(sugg) = self.map.get(&*fn_name.as_str());
498             let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
499             if match_type(cx, ty, &paths::EARLY_CONTEXT)
500                 || match_type(cx, ty, &paths::LATE_CONTEXT);
501             then {
502                 span_lint_and_help(
503                     cx,
504                     COMPILER_LINT_FUNCTIONS,
505                     path.ident.span,
506                     "usage of a compiler lint function",
507                     None,
508                     &format!("please use the Clippy variant of this function: `{}`", sugg),
509                 );
510             }
511         }
512     }
513 }
514
515 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
516
517 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
518     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
519         if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
520             return;
521         }
522
523         let (method_names, arg_lists, spans) = method_calls(expr, 2);
524         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
525         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
526         if_chain! {
527             if let ["expn_data", "outer_expn"] = method_names.as_slice();
528             let args = arg_lists[1];
529             if args.len() == 1;
530             let self_arg = &args[0];
531             let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
532             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
533             then {
534                 span_lint_and_sugg(
535                     cx,
536                     OUTER_EXPN_EXPN_DATA,
537                     spans[1].with_hi(expr.span.hi()),
538                     "usage of `outer_expn().expn_data()`",
539                     "try",
540                     "outer_expn_data()".to_string(),
541                     Applicability::MachineApplicable,
542                 );
543             }
544         }
545     }
546 }
547
548 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
549
550 impl EarlyLintPass for ProduceIce {
551     fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
552         if is_trigger_fn(fn_kind) {
553             panic!("Would you like some help with that?");
554         }
555     }
556 }
557
558 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
559     match fn_kind {
560         FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
561         FnKind::Closure(..) => false,
562     }
563 }
564
565 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
566
567 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
568     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
569         if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
570             return;
571         }
572
573         if_chain! {
574             if let ExprKind::Call(ref func, ref and_then_args) = expr.kind;
575             if let ExprKind::Path(ref path) = func.kind;
576             if match_qpath(path, &["span_lint_and_then"]);
577             if and_then_args.len() == 5;
578             if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
579             let body = cx.tcx.hir().body(*body_id);
580             if let ExprKind::Block(block, _) = &body.value.kind;
581             let stmts = &block.stmts;
582             if stmts.len() == 1 && block.expr.is_none();
583             if let StmtKind::Semi(only_expr) = &stmts[0].kind;
584             if let ExprKind::MethodCall(ref ps, _, ref span_call_args, _) = &only_expr.kind;
585             let and_then_snippets = get_and_then_snippets(cx, and_then_args);
586             let mut sle = SpanlessEq::new(cx).deny_side_effects();
587             then {
588                 match &*ps.ident.as_str() {
589                     "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
590                         suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
591                     },
592                     "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
593                         let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
594                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
595                     },
596                     "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
597                         let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
598                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
599                     },
600                     "help" => {
601                         let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
602                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
603                     }
604                     "note" => {
605                         let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
606                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
607                     }
608                     _  => (),
609                 }
610             }
611         }
612     }
613 }
614
615 struct AndThenSnippets<'a> {
616     cx: Cow<'a, str>,
617     lint: Cow<'a, str>,
618     span: Cow<'a, str>,
619     msg: Cow<'a, str>,
620 }
621
622 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
623     let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
624     let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
625     let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
626     let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
627
628     AndThenSnippets {
629         cx: cx_snippet,
630         lint: lint_snippet,
631         span: span_snippet,
632         msg: msg_snippet,
633     }
634 }
635
636 struct SpanSuggestionSnippets<'a> {
637     help: Cow<'a, str>,
638     sugg: Cow<'a, str>,
639     applicability: Cow<'a, str>,
640 }
641
642 fn span_suggestion_snippets<'a, 'hir>(
643     cx: &LateContext<'_>,
644     span_call_args: &'hir [Expr<'hir>],
645 ) -> SpanSuggestionSnippets<'a> {
646     let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
647     let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
648     let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
649
650     SpanSuggestionSnippets {
651         help: help_snippet,
652         sugg: sugg_snippet,
653         applicability: applicability_snippet,
654     }
655 }
656
657 fn suggest_suggestion(
658     cx: &LateContext<'_>,
659     expr: &Expr<'_>,
660     and_then_snippets: &AndThenSnippets<'_>,
661     span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
662 ) {
663     span_lint_and_sugg(
664         cx,
665         COLLAPSIBLE_SPAN_LINT_CALLS,
666         expr.span,
667         "this call is collapsible",
668         "collapse into",
669         format!(
670             "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
671             and_then_snippets.cx,
672             and_then_snippets.lint,
673             and_then_snippets.span,
674             and_then_snippets.msg,
675             span_suggestion_snippets.help,
676             span_suggestion_snippets.sugg,
677             span_suggestion_snippets.applicability
678         ),
679         Applicability::MachineApplicable,
680     );
681 }
682
683 fn suggest_help(
684     cx: &LateContext<'_>,
685     expr: &Expr<'_>,
686     and_then_snippets: &AndThenSnippets<'_>,
687     help: &str,
688     with_span: bool,
689 ) {
690     let option_span = if with_span {
691         format!("Some({})", and_then_snippets.span)
692     } else {
693         "None".to_string()
694     };
695
696     span_lint_and_sugg(
697         cx,
698         COLLAPSIBLE_SPAN_LINT_CALLS,
699         expr.span,
700         "this call is collapsible",
701         "collapse into",
702         format!(
703             "span_lint_and_help({}, {}, {}, {}, {}, {})",
704             and_then_snippets.cx,
705             and_then_snippets.lint,
706             and_then_snippets.span,
707             and_then_snippets.msg,
708             &option_span,
709             help
710         ),
711         Applicability::MachineApplicable,
712     );
713 }
714
715 fn suggest_note(
716     cx: &LateContext<'_>,
717     expr: &Expr<'_>,
718     and_then_snippets: &AndThenSnippets<'_>,
719     note: &str,
720     with_span: bool,
721 ) {
722     let note_span = if with_span {
723         format!("Some({})", and_then_snippets.span)
724     } else {
725         "None".to_string()
726     };
727
728     span_lint_and_sugg(
729         cx,
730         COLLAPSIBLE_SPAN_LINT_CALLS,
731         expr.span,
732         "this call is collspible",
733         "collapse into",
734         format!(
735             "span_lint_and_note({}, {}, {}, {}, {}, {})",
736             and_then_snippets.cx,
737             and_then_snippets.lint,
738             and_then_snippets.span,
739             and_then_snippets.msg,
740             note_span,
741             note
742         ),
743         Applicability::MachineApplicable,
744     );
745 }
746
747 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
748
749 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
750     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
751         if !run_lints(cx, &[MATCH_TYPE_ON_DIAGNOSTIC_ITEM], expr.hir_id) {
752             return;
753         }
754
755         if_chain! {
756             // Check if this is a call to utils::match_type()
757             if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
758             if let ExprKind::Path(fn_qpath) = &fn_path.kind;
759             if match_qpath(&fn_qpath, &["utils", "match_type"]);
760             // Extract the path to the matched type
761             if let Some(segments) = path_to_matched_type(cx, ty_path);
762             let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
763             if let Some(ty_did) = path_to_res(cx, &segments[..]).and_then(|res| res.opt_def_id());
764             // Check if the matched type is a diagnostic item
765             let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
766             if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
767             then {
768                 let cx_snippet = snippet(cx, context.span, "_");
769                 let ty_snippet = snippet(cx, ty.span, "_");
770
771                 span_lint_and_sugg(
772                     cx,
773                     MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
774                     expr.span,
775                     "usage of `utils::match_type()` on a type diagnostic item",
776                     "try",
777                     format!("utils::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
778                     Applicability::MaybeIncorrect,
779                 );
780             }
781         }
782     }
783 }
784
785 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
786     use rustc_hir::ItemKind;
787
788     match &expr.kind {
789         ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
790         ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
791             Res::Local(hir_id) => {
792                 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
793                 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
794                     if let Some(init) = local.init {
795                         return path_to_matched_type(cx, init);
796                     }
797                 }
798             },
799             Res::Def(DefKind::Const | DefKind::Static, def_id) => {
800                 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
801                     if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
802                         let body = cx.tcx.hir().body(body_id);
803                         return path_to_matched_type(cx, &body.value);
804                     }
805                 }
806             },
807             _ => {},
808         },
809         ExprKind::Array(exprs) => {
810             let segments: Vec<SymbolStr> = exprs
811                 .iter()
812                 .filter_map(|expr| {
813                     if let ExprKind::Lit(lit) = &expr.kind {
814                         if let LitKind::Str(sym, _) = lit.node {
815                             return Some(sym.as_str());
816                         }
817                     }
818
819                     None
820                 })
821                 .collect();
822
823             if segments.len() == exprs.len() {
824                 return Some(segments);
825             }
826         },
827         _ => {},
828     }
829
830     None
831 }
832
833 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
834 // module.  That's all it does and all it needs to do.
835 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
836     if path_to_res(cx, path).is_some() {
837         return true;
838     }
839
840     // Some implementations can't be found by `path_to_res`, particularly inherent
841     // implementations of native types. Check lang items.
842     let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
843     let lang_items = cx.tcx.lang_items();
844     for lang_item in lang_items.items() {
845         if let Some(def_id) = lang_item {
846             let lang_item_path = cx.get_def_path(*def_id);
847             if path_syms.starts_with(&lang_item_path) {
848                 if let [item] = &path_syms[lang_item_path.len()..] {
849                     for child in cx.tcx.item_children(*def_id) {
850                         if child.ident.name == *item {
851                             return true;
852                         }
853                     }
854                 }
855             }
856         }
857     }
858
859     false
860 }
861
862 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
863
864 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
865     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
866         let local_def_id = &cx.tcx.parent_module(item.hir_id);
867         let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
868         if_chain! {
869             if mod_name.as_str() == "paths";
870             if let hir::ItemKind::Const(ty, body_id) = item.kind;
871             let ty = hir_ty_to_ty(cx.tcx, ty);
872             if let ty::Array(el_ty, _) = &ty.kind();
873             if let ty::Ref(_, el_ty, _) = &el_ty.kind();
874             if el_ty.is_str();
875             let body = cx.tcx.hir().body(body_id);
876             let typeck_results = cx.tcx.typeck_body(body_id);
877             if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
878             let path: Vec<&str> = path.iter().map(|x| {
879                     if let Constant::Str(s) = x {
880                         s.as_str()
881                     } else {
882                         // We checked the type of the constant above
883                         unreachable!()
884                     }
885                 }).collect();
886             if !check_path(cx, &path[..]);
887             then {
888                 span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
889             }
890         }
891     }
892 }
893
894 #[derive(Default)]
895 pub struct InterningDefinedSymbol {
896     // Maps the symbol value to the constant DefId.
897     symbol_map: FxHashMap<u32, DefId>,
898 }
899
900 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
901
902 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
903     fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
904         if !self.symbol_map.is_empty() {
905             return;
906         }
907
908         for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
909             if let Some(Res::Def(_, def_id)) = path_to_res(cx, module) {
910                 for item in cx.tcx.item_children(def_id).iter() {
911                     if_chain! {
912                         if let Res::Def(DefKind::Const, item_def_id) = item.res;
913                         let ty = cx.tcx.type_of(item_def_id);
914                         if match_type(cx, ty, &paths::SYMBOL);
915                         if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
916                         if let Ok(value) = value.to_u32();
917                         then {
918                             self.symbol_map.insert(value, item_def_id);
919                         }
920                     }
921                 }
922             }
923         }
924     }
925
926     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
927         if_chain! {
928             if let ExprKind::Call(func, [arg]) = &expr.kind;
929             if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
930             if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
931             if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
932             let value = Symbol::intern(&arg).as_u32();
933             if let Some(&def_id) = self.symbol_map.get(&value);
934             then {
935                 span_lint_and_sugg(
936                     cx,
937                     INTERNING_DEFINED_SYMBOL,
938                     is_expn_of(expr.span, "sym").unwrap_or(expr.span),
939                     "interning a defined symbol",
940                     "try",
941                     cx.tcx.def_path_str(def_id),
942                     Applicability::MachineApplicable,
943                 );
944             }
945         }
946         if let ExprKind::Binary(op, left, right) = expr.kind {
947             if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
948                 let data = [
949                     (left, self.symbol_str_expr(left, cx)),
950                     (right, self.symbol_str_expr(right, cx)),
951                 ];
952                 match data {
953                     // both operands are a symbol string
954                     [(_, Some(left)), (_, Some(right))] => {
955                         span_lint_and_sugg(
956                             cx,
957                             UNNECESSARY_SYMBOL_STR,
958                             expr.span,
959                             "unnecessary `Symbol` to string conversion",
960                             "try",
961                             format!(
962                                 "{} {} {}",
963                                 left.as_symbol_snippet(cx),
964                                 op.node.as_str(),
965                                 right.as_symbol_snippet(cx),
966                             ),
967                             Applicability::MachineApplicable,
968                         );
969                     },
970                     // one of the operands is a symbol string
971                     [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
972                         // creating an owned string for comparison
973                         if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
974                             span_lint_and_sugg(
975                                 cx,
976                                 UNNECESSARY_SYMBOL_STR,
977                                 expr.span,
978                                 "unnecessary string allocation",
979                                 "try",
980                                 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
981                                 Applicability::MachineApplicable,
982                             );
983                         }
984                     },
985                     // nothing found
986                     [(_, None), (_, None)] => {},
987                 }
988             }
989         }
990     }
991 }
992
993 impl InterningDefinedSymbol {
994     fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
995         static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
996         static SYMBOL_STR_PATHS: &[&[&str]] = &[
997             &paths::SYMBOL_AS_STR,
998             &paths::SYMBOL_TO_IDENT_STRING,
999             &paths::TO_STRING_METHOD,
1000         ];
1001         // SymbolStr might be de-referenced: `&*symbol.as_str()`
1002         let call = if_chain! {
1003             if let ExprKind::AddrOf(_, _, e) = expr.kind;
1004             if let ExprKind::Unary(UnOp::UnDeref, e) = e.kind;
1005             then { e } else { expr }
1006         };
1007         if_chain! {
1008             // is a method call
1009             if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1010             if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1011             let ty = cx.typeck_results().expr_ty(item);
1012             // ...on either an Ident or a Symbol
1013             if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1014                 Some(false)
1015             } else if match_type(cx, ty, &paths::IDENT) {
1016                 Some(true)
1017             } else {
1018                 None
1019             };
1020             // ...which converts it to a string
1021             let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1022             if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1023             then {
1024                 let is_to_owned = path.last().unwrap().ends_with("string");
1025                 return Some(SymbolStrExpr::Expr {
1026                     item,
1027                     is_ident,
1028                     is_to_owned,
1029                 });
1030             }
1031         }
1032         // is a string constant
1033         if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1034             let value = Symbol::intern(&s).as_u32();
1035             // ...which matches a symbol constant
1036             if let Some(&def_id) = self.symbol_map.get(&value) {
1037                 return Some(SymbolStrExpr::Const(def_id));
1038             }
1039         }
1040         None
1041     }
1042 }
1043
1044 enum SymbolStrExpr<'tcx> {
1045     /// a string constant with a corresponding symbol constant
1046     Const(DefId),
1047     /// a "symbol to string" expression like `symbol.as_str()`
1048     Expr {
1049         /// part that evaluates to `Symbol` or `Ident`
1050         item: &'tcx Expr<'tcx>,
1051         is_ident: bool,
1052         /// whether an owned `String` is created like `to_ident_string()`
1053         is_to_owned: bool,
1054     },
1055 }
1056
1057 impl<'tcx> SymbolStrExpr<'tcx> {
1058     /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1059     fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1060         match *self {
1061             Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1062             Self::Expr { item, is_ident, .. } => {
1063                 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1064                 if is_ident {
1065                     // get `Ident.name`
1066                     snip.to_mut().push_str(".name");
1067                 }
1068                 snip
1069             },
1070         }
1071     }
1072 }