]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/internal_lints.rs
Auto merge of #81354 - SkiFire13:binary-search-assume, r=nagisa
[rust.git] / src / tools / clippy / clippy_lints / src / utils / internal_lints.rs
1 use crate::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg};
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::match_type;
5 use clippy_utils::{is_expn_of, match_def_path, match_qpath, method_calls, path_to_res, paths, run_lints, SpanlessEq};
6 use if_chain::if_chain;
7 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, ModKind, 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.items.iter().find(|item| item.ident.name.as_str() == "utils") {
305             if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
306                 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
307                     if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
308                         let mut last_name: Option<SymbolStr> = None;
309                         for item in items {
310                             let name = item.ident.as_str();
311                             if let Some(ref last_name) = last_name {
312                                 if **last_name > *name {
313                                     span_lint(
314                                         cx,
315                                         CLIPPY_LINTS_INTERNAL,
316                                         item.span,
317                                         "this constant should be before the previous constant due to lexical \
318                                          ordering",
319                                     );
320                                 }
321                             }
322                             last_name = Some(name);
323                         }
324                     }
325                 }
326             }
327         }
328     }
329 }
330
331 #[derive(Clone, Debug, Default)]
332 pub struct LintWithoutLintPass {
333     declared_lints: FxHashMap<Symbol, Span>,
334     registered_lints: FxHashSet<Symbol>,
335 }
336
337 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
338
339 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
340     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
341         if !run_lints(cx, &[DEFAULT_LINT], item.hir_id()) {
342             return;
343         }
344
345         if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
346             if is_lint_ref_type(cx, ty) {
347                 let expr = &cx.tcx.hir().body(body_id).value;
348                 if_chain! {
349                     if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
350                     if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
351                     let field = fields
352                         .iter()
353                         .find(|f| f.ident.as_str() == "desc")
354                         .expect("lints must have a description field");
355                     if let ExprKind::Lit(Spanned {
356                         node: LitKind::Str(ref sym, _),
357                         ..
358                     }) = field.expr.kind;
359                     if sym.as_str() == "default lint description";
360
361                     then {
362                         span_lint(
363                             cx,
364                             DEFAULT_LINT,
365                             item.span,
366                             &format!("the lint `{}` has the default lint description", item.ident.name),
367                         );
368                     }
369                 }
370                 self.declared_lints.insert(item.ident.name, item.span);
371             }
372         } else if is_expn_of(item.span, "impl_lint_pass").is_some()
373             || is_expn_of(item.span, "declare_lint_pass").is_some()
374         {
375             if let hir::ItemKind::Impl(hir::Impl {
376                 of_trait: None,
377                 items: ref impl_item_refs,
378                 ..
379             }) = item.kind
380             {
381                 let mut collector = LintCollector {
382                     output: &mut self.registered_lints,
383                     cx,
384                 };
385                 let body_id = cx.tcx.hir().body_owned_by(
386                     impl_item_refs
387                         .iter()
388                         .find(|iiref| iiref.ident.as_str() == "get_lints")
389                         .expect("LintPass needs to implement get_lints")
390                         .id
391                         .hir_id(),
392                 );
393                 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
394             }
395         }
396     }
397
398     fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
399         if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
400             return;
401         }
402
403         for (lint_name, &lint_span) in &self.declared_lints {
404             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
405             // file points to "<rustc macros>".
406             // `compiletest-rs` thinks that's an error in a different file and
407             // just ignores it. This causes the test in compile-fail/lint_pass
408             // not able to capture the error.
409             // Therefore, we need to climb the macro expansion tree and find the
410             // actual span that invoked `declare_tool_lint!`:
411             let lint_span = lint_span.ctxt().outer_expn_data().call_site;
412
413             if !self.registered_lints.contains(lint_name) {
414                 span_lint(
415                     cx,
416                     LINT_WITHOUT_LINT_PASS,
417                     lint_span,
418                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
419                 );
420             }
421         }
422     }
423 }
424
425 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
426     if let TyKind::Rptr(
427         _,
428         MutTy {
429             ty: ref inner,
430             mutbl: Mutability::Not,
431         },
432     ) = ty.kind
433     {
434         if let TyKind::Path(ref path) = inner.kind {
435             if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
436                 return match_def_path(cx, def_id, &paths::LINT);
437             }
438         }
439     }
440
441     false
442 }
443
444 struct LintCollector<'a, 'tcx> {
445     output: &'a mut FxHashSet<Symbol>,
446     cx: &'a LateContext<'tcx>,
447 }
448
449 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
450     type Map = Map<'tcx>;
451
452     fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
453         if path.segments.len() == 1 {
454             self.output.insert(path.segments[0].ident.name);
455         }
456     }
457
458     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
459         NestedVisitorMap::All(self.cx.tcx.hir())
460     }
461 }
462
463 #[derive(Clone, Default)]
464 pub struct CompilerLintFunctions {
465     map: FxHashMap<&'static str, &'static str>,
466 }
467
468 impl CompilerLintFunctions {
469     #[must_use]
470     pub fn new() -> Self {
471         let mut map = FxHashMap::default();
472         map.insert("span_lint", "utils::span_lint");
473         map.insert("struct_span_lint", "utils::span_lint");
474         map.insert("lint", "utils::span_lint");
475         map.insert("span_lint_note", "utils::span_lint_and_note");
476         map.insert("span_lint_help", "utils::span_lint_and_help");
477         Self { map }
478     }
479 }
480
481 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
482
483 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
484     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
485         if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
486             return;
487         }
488
489         if_chain! {
490             if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
491             let fn_name = path.ident;
492             if let Some(sugg) = self.map.get(&*fn_name.as_str());
493             let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
494             if match_type(cx, ty, &paths::EARLY_CONTEXT)
495                 || match_type(cx, ty, &paths::LATE_CONTEXT);
496             then {
497                 span_lint_and_help(
498                     cx,
499                     COMPILER_LINT_FUNCTIONS,
500                     path.ident.span,
501                     "usage of a compiler lint function",
502                     None,
503                     &format!("please use the Clippy variant of this function: `{}`", sugg),
504                 );
505             }
506         }
507     }
508 }
509
510 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
511
512 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
513     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
514         if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
515             return;
516         }
517
518         let (method_names, arg_lists, spans) = method_calls(expr, 2);
519         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
520         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
521         if_chain! {
522             if let ["expn_data", "outer_expn"] = method_names.as_slice();
523             let args = arg_lists[1];
524             if args.len() == 1;
525             let self_arg = &args[0];
526             let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
527             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
528             then {
529                 span_lint_and_sugg(
530                     cx,
531                     OUTER_EXPN_EXPN_DATA,
532                     spans[1].with_hi(expr.span.hi()),
533                     "usage of `outer_expn().expn_data()`",
534                     "try",
535                     "outer_expn_data()".to_string(),
536                     Applicability::MachineApplicable,
537                 );
538             }
539         }
540     }
541 }
542
543 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
544
545 impl EarlyLintPass for ProduceIce {
546     fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
547         if is_trigger_fn(fn_kind) {
548             panic!("Would you like some help with that?");
549         }
550     }
551 }
552
553 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
554     match fn_kind {
555         FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
556         FnKind::Closure(..) => false,
557     }
558 }
559
560 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
561
562 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
563     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
564         if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
565             return;
566         }
567
568         if_chain! {
569             if let ExprKind::Call(ref func, ref and_then_args) = expr.kind;
570             if let ExprKind::Path(ref path) = func.kind;
571             if match_qpath(path, &["span_lint_and_then"]);
572             if and_then_args.len() == 5;
573             if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
574             let body = cx.tcx.hir().body(*body_id);
575             if let ExprKind::Block(block, _) = &body.value.kind;
576             let stmts = &block.stmts;
577             if stmts.len() == 1 && block.expr.is_none();
578             if let StmtKind::Semi(only_expr) = &stmts[0].kind;
579             if let ExprKind::MethodCall(ref ps, _, ref span_call_args, _) = &only_expr.kind;
580             let and_then_snippets = get_and_then_snippets(cx, and_then_args);
581             let mut sle = SpanlessEq::new(cx).deny_side_effects();
582             then {
583                 match &*ps.ident.as_str() {
584                     "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
585                         suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
586                     },
587                     "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
588                         let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
589                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
590                     },
591                     "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
592                         let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
593                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
594                     },
595                     "help" => {
596                         let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
597                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
598                     }
599                     "note" => {
600                         let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
601                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
602                     }
603                     _  => (),
604                 }
605             }
606         }
607     }
608 }
609
610 struct AndThenSnippets<'a> {
611     cx: Cow<'a, str>,
612     lint: Cow<'a, str>,
613     span: Cow<'a, str>,
614     msg: Cow<'a, str>,
615 }
616
617 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
618     let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
619     let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
620     let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
621     let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
622
623     AndThenSnippets {
624         cx: cx_snippet,
625         lint: lint_snippet,
626         span: span_snippet,
627         msg: msg_snippet,
628     }
629 }
630
631 struct SpanSuggestionSnippets<'a> {
632     help: Cow<'a, str>,
633     sugg: Cow<'a, str>,
634     applicability: Cow<'a, str>,
635 }
636
637 fn span_suggestion_snippets<'a, 'hir>(
638     cx: &LateContext<'_>,
639     span_call_args: &'hir [Expr<'hir>],
640 ) -> SpanSuggestionSnippets<'a> {
641     let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
642     let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
643     let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
644
645     SpanSuggestionSnippets {
646         help: help_snippet,
647         sugg: sugg_snippet,
648         applicability: applicability_snippet,
649     }
650 }
651
652 fn suggest_suggestion(
653     cx: &LateContext<'_>,
654     expr: &Expr<'_>,
655     and_then_snippets: &AndThenSnippets<'_>,
656     span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
657 ) {
658     span_lint_and_sugg(
659         cx,
660         COLLAPSIBLE_SPAN_LINT_CALLS,
661         expr.span,
662         "this call is collapsible",
663         "collapse into",
664         format!(
665             "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
666             and_then_snippets.cx,
667             and_then_snippets.lint,
668             and_then_snippets.span,
669             and_then_snippets.msg,
670             span_suggestion_snippets.help,
671             span_suggestion_snippets.sugg,
672             span_suggestion_snippets.applicability
673         ),
674         Applicability::MachineApplicable,
675     );
676 }
677
678 fn suggest_help(
679     cx: &LateContext<'_>,
680     expr: &Expr<'_>,
681     and_then_snippets: &AndThenSnippets<'_>,
682     help: &str,
683     with_span: bool,
684 ) {
685     let option_span = if with_span {
686         format!("Some({})", and_then_snippets.span)
687     } else {
688         "None".to_string()
689     };
690
691     span_lint_and_sugg(
692         cx,
693         COLLAPSIBLE_SPAN_LINT_CALLS,
694         expr.span,
695         "this call is collapsible",
696         "collapse into",
697         format!(
698             "span_lint_and_help({}, {}, {}, {}, {}, {})",
699             and_then_snippets.cx,
700             and_then_snippets.lint,
701             and_then_snippets.span,
702             and_then_snippets.msg,
703             &option_span,
704             help
705         ),
706         Applicability::MachineApplicable,
707     );
708 }
709
710 fn suggest_note(
711     cx: &LateContext<'_>,
712     expr: &Expr<'_>,
713     and_then_snippets: &AndThenSnippets<'_>,
714     note: &str,
715     with_span: bool,
716 ) {
717     let note_span = if with_span {
718         format!("Some({})", and_then_snippets.span)
719     } else {
720         "None".to_string()
721     };
722
723     span_lint_and_sugg(
724         cx,
725         COLLAPSIBLE_SPAN_LINT_CALLS,
726         expr.span,
727         "this call is collspible",
728         "collapse into",
729         format!(
730             "span_lint_and_note({}, {}, {}, {}, {}, {})",
731             and_then_snippets.cx,
732             and_then_snippets.lint,
733             and_then_snippets.span,
734             and_then_snippets.msg,
735             note_span,
736             note
737         ),
738         Applicability::MachineApplicable,
739     );
740 }
741
742 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
743
744 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
745     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
746         if !run_lints(cx, &[MATCH_TYPE_ON_DIAGNOSTIC_ITEM], expr.hir_id) {
747             return;
748         }
749
750         if_chain! {
751             // Check if this is a call to utils::match_type()
752             if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
753             if let ExprKind::Path(fn_qpath) = &fn_path.kind;
754             if match_qpath(&fn_qpath, &["utils", "match_type"]);
755             // Extract the path to the matched type
756             if let Some(segments) = path_to_matched_type(cx, ty_path);
757             let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
758             if let Some(ty_did) = path_to_res(cx, &segments[..]).opt_def_id();
759             // Check if the matched type is a diagnostic item
760             let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
761             if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
762             then {
763                 let cx_snippet = snippet(cx, context.span, "_");
764                 let ty_snippet = snippet(cx, ty.span, "_");
765
766                 span_lint_and_sugg(
767                     cx,
768                     MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
769                     expr.span,
770                     "usage of `utils::match_type()` on a type diagnostic item",
771                     "try",
772                     format!("utils::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
773                     Applicability::MaybeIncorrect,
774                 );
775             }
776         }
777     }
778 }
779
780 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
781     use rustc_hir::ItemKind;
782
783     match &expr.kind {
784         ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
785         ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
786             Res::Local(hir_id) => {
787                 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
788                 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
789                     if let Some(init) = local.init {
790                         return path_to_matched_type(cx, init);
791                     }
792                 }
793             },
794             Res::Def(DefKind::Const | DefKind::Static, def_id) => {
795                 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
796                     if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
797                         let body = cx.tcx.hir().body(body_id);
798                         return path_to_matched_type(cx, &body.value);
799                     }
800                 }
801             },
802             _ => {},
803         },
804         ExprKind::Array(exprs) => {
805             let segments: Vec<SymbolStr> = exprs
806                 .iter()
807                 .filter_map(|expr| {
808                     if let ExprKind::Lit(lit) = &expr.kind {
809                         if let LitKind::Str(sym, _) = lit.node {
810                             return Some(sym.as_str());
811                         }
812                     }
813
814                     None
815                 })
816                 .collect();
817
818             if segments.len() == exprs.len() {
819                 return Some(segments);
820             }
821         },
822         _ => {},
823     }
824
825     None
826 }
827
828 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
829 // module.  That's all it does and all it needs to do.
830 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
831     if path_to_res(cx, path) != Res::Err {
832         return true;
833     }
834
835     // Some implementations can't be found by `path_to_res`, particularly inherent
836     // implementations of native types. Check lang items.
837     let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
838     let lang_items = cx.tcx.lang_items();
839     for item_def_id in lang_items.items().iter().flatten() {
840         let lang_item_path = cx.get_def_path(*item_def_id);
841         if path_syms.starts_with(&lang_item_path) {
842             if let [item] = &path_syms[lang_item_path.len()..] {
843                 for child in cx.tcx.item_children(*item_def_id) {
844                     if child.ident.name == *item {
845                         return true;
846                     }
847                 }
848             }
849         }
850     }
851
852     false
853 }
854
855 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
856
857 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
858     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
859         let local_def_id = &cx.tcx.parent_module(item.hir_id());
860         let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
861         if_chain! {
862             if mod_name.as_str() == "paths";
863             if let hir::ItemKind::Const(ty, body_id) = item.kind;
864             let ty = hir_ty_to_ty(cx.tcx, ty);
865             if let ty::Array(el_ty, _) = &ty.kind();
866             if let ty::Ref(_, el_ty, _) = &el_ty.kind();
867             if el_ty.is_str();
868             let body = cx.tcx.hir().body(body_id);
869             let typeck_results = cx.tcx.typeck_body(body_id);
870             if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
871             let path: Vec<&str> = path.iter().map(|x| {
872                     if let Constant::Str(s) = x {
873                         s.as_str()
874                     } else {
875                         // We checked the type of the constant above
876                         unreachable!()
877                     }
878                 }).collect();
879             if !check_path(cx, &path[..]);
880             then {
881                 span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
882             }
883         }
884     }
885 }
886
887 #[derive(Default)]
888 pub struct InterningDefinedSymbol {
889     // Maps the symbol value to the constant DefId.
890     symbol_map: FxHashMap<u32, DefId>,
891 }
892
893 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
894
895 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
896     fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
897         if !self.symbol_map.is_empty() {
898             return;
899         }
900
901         for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
902             if let Some(def_id) = path_to_res(cx, module).opt_def_id() {
903                 for item in cx.tcx.item_children(def_id).iter() {
904                     if_chain! {
905                         if let Res::Def(DefKind::Const, item_def_id) = item.res;
906                         let ty = cx.tcx.type_of(item_def_id);
907                         if match_type(cx, ty, &paths::SYMBOL);
908                         if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
909                         if let Ok(value) = value.to_u32();
910                         then {
911                             self.symbol_map.insert(value, item_def_id);
912                         }
913                     }
914                 }
915             }
916         }
917     }
918
919     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
920         if_chain! {
921             if let ExprKind::Call(func, [arg]) = &expr.kind;
922             if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
923             if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
924             if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
925             let value = Symbol::intern(&arg).as_u32();
926             if let Some(&def_id) = self.symbol_map.get(&value);
927             then {
928                 span_lint_and_sugg(
929                     cx,
930                     INTERNING_DEFINED_SYMBOL,
931                     is_expn_of(expr.span, "sym").unwrap_or(expr.span),
932                     "interning a defined symbol",
933                     "try",
934                     cx.tcx.def_path_str(def_id),
935                     Applicability::MachineApplicable,
936                 );
937             }
938         }
939         if let ExprKind::Binary(op, left, right) = expr.kind {
940             if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
941                 let data = [
942                     (left, self.symbol_str_expr(left, cx)),
943                     (right, self.symbol_str_expr(right, cx)),
944                 ];
945                 match data {
946                     // both operands are a symbol string
947                     [(_, Some(left)), (_, Some(right))] => {
948                         span_lint_and_sugg(
949                             cx,
950                             UNNECESSARY_SYMBOL_STR,
951                             expr.span,
952                             "unnecessary `Symbol` to string conversion",
953                             "try",
954                             format!(
955                                 "{} {} {}",
956                                 left.as_symbol_snippet(cx),
957                                 op.node.as_str(),
958                                 right.as_symbol_snippet(cx),
959                             ),
960                             Applicability::MachineApplicable,
961                         );
962                     },
963                     // one of the operands is a symbol string
964                     [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
965                         // creating an owned string for comparison
966                         if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
967                             span_lint_and_sugg(
968                                 cx,
969                                 UNNECESSARY_SYMBOL_STR,
970                                 expr.span,
971                                 "unnecessary string allocation",
972                                 "try",
973                                 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
974                                 Applicability::MachineApplicable,
975                             );
976                         }
977                     },
978                     // nothing found
979                     [(_, None), (_, None)] => {},
980                 }
981             }
982         }
983     }
984 }
985
986 impl InterningDefinedSymbol {
987     fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
988         static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
989         static SYMBOL_STR_PATHS: &[&[&str]] = &[
990             &paths::SYMBOL_AS_STR,
991             &paths::SYMBOL_TO_IDENT_STRING,
992             &paths::TO_STRING_METHOD,
993         ];
994         // SymbolStr might be de-referenced: `&*symbol.as_str()`
995         let call = if_chain! {
996             if let ExprKind::AddrOf(_, _, e) = expr.kind;
997             if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
998             then { e } else { expr }
999         };
1000         if_chain! {
1001             // is a method call
1002             if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1003             if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1004             let ty = cx.typeck_results().expr_ty(item);
1005             // ...on either an Ident or a Symbol
1006             if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1007                 Some(false)
1008             } else if match_type(cx, ty, &paths::IDENT) {
1009                 Some(true)
1010             } else {
1011                 None
1012             };
1013             // ...which converts it to a string
1014             let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1015             if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1016             then {
1017                 let is_to_owned = path.last().unwrap().ends_with("string");
1018                 return Some(SymbolStrExpr::Expr {
1019                     item,
1020                     is_ident,
1021                     is_to_owned,
1022                 });
1023             }
1024         }
1025         // is a string constant
1026         if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1027             let value = Symbol::intern(&s).as_u32();
1028             // ...which matches a symbol constant
1029             if let Some(&def_id) = self.symbol_map.get(&value) {
1030                 return Some(SymbolStrExpr::Const(def_id));
1031             }
1032         }
1033         None
1034     }
1035 }
1036
1037 enum SymbolStrExpr<'tcx> {
1038     /// a string constant with a corresponding symbol constant
1039     Const(DefId),
1040     /// a "symbol to string" expression like `symbol.as_str()`
1041     Expr {
1042         /// part that evaluates to `Symbol` or `Ident`
1043         item: &'tcx Expr<'tcx>,
1044         is_ident: bool,
1045         /// whether an owned `String` is created like `to_ident_string()`
1046         is_to_owned: bool,
1047     },
1048 }
1049
1050 impl<'tcx> SymbolStrExpr<'tcx> {
1051     /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1052     fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1053         match *self {
1054             Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1055             Self::Expr { item, is_ident, .. } => {
1056                 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1057                 if is_ident {
1058                     // get `Ident.name`
1059                     snip.to_mut().push_str(".name");
1060                 }
1061                 snip
1062             },
1063         }
1064     }
1065 }