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