]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/internal_lints.rs
Rollup merge of #102675 - ouz-a:mir-technical-debt, r=oli-obk
[rust.git] / clippy_lints / src / utils / internal_lints.rs
1 use crate::utils::internal_lints::metadata_collector::is_deprecated_lint;
2 use clippy_utils::consts::{constant_simple, Constant};
3 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
4 use clippy_utils::macros::root_macro_call_first_node;
5 use clippy_utils::source::{snippet, snippet_with_applicability};
6 use clippy_utils::ty::match_type;
7 use clippy_utils::{
8     def_path_res, higher, is_else_clause, is_expn_of, is_expr_path_def_path, is_lint_allowed, match_any_def_paths,
9     match_def_path, method_calls, paths, peel_blocks_with_stmt, peel_hir_expr_refs, SpanlessEq,
10 };
11 use if_chain::if_chain;
12 use rustc_ast as ast;
13 use rustc_ast::ast::{Crate, ItemKind, LitKind, ModKind, NodeId};
14 use rustc_ast::visit::FnKind;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_errors::Applicability;
17 use rustc_hir as hir;
18 use rustc_hir::def::{DefKind, Namespace, Res};
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::hir_id::CRATE_HIR_ID;
21 use rustc_hir::intravisit::Visitor;
22 use rustc_hir::{
23     BinOpKind, Block, Closure, Expr, ExprKind, HirId, Item, Local, MutTy, Mutability, Node, Path, Stmt, StmtKind,
24     TyKind, UnOp,
25 };
26 use rustc_hir_analysis::hir_ty_to_ty;
27 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
28 use rustc_middle::hir::nested_filter;
29 use rustc_middle::mir::interpret::{Allocation, ConstValue, GlobalAlloc};
30 use rustc_middle::ty::{
31     self, fast_reject::SimplifiedTypeGen, subst::GenericArgKind, AssocKind, DefIdTree, FloatTy, Ty,
32 };
33 use rustc_semver::RustcVersion;
34 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
35 use rustc_span::source_map::Spanned;
36 use rustc_span::symbol::{Ident, Symbol};
37 use rustc_span::{sym, BytePos, Span};
38
39 use std::borrow::{Borrow, Cow};
40 use std::str;
41
42 #[cfg(feature = "internal")]
43 pub mod metadata_collector;
44
45 declare_clippy_lint! {
46     /// ### What it does
47     /// Checks for various things we like to keep tidy in clippy.
48     ///
49     /// ### Why is this bad?
50     /// We like to pretend we're an example of tidy code.
51     ///
52     /// ### Example
53     /// Wrong ordering of the util::paths constants.
54     pub CLIPPY_LINTS_INTERNAL,
55     internal,
56     "various things that will negatively affect your clippy experience"
57 }
58
59 declare_clippy_lint! {
60     /// ### What it does
61     /// Ensures every lint is associated to a `LintPass`.
62     ///
63     /// ### Why is this bad?
64     /// The compiler only knows lints via a `LintPass`. Without
65     /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
66     /// know the name of the lint.
67     ///
68     /// ### Known problems
69     /// Only checks for lints associated using the
70     /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
71     ///
72     /// ### Example
73     /// ```rust,ignore
74     /// declare_lint! { pub LINT_1, ... }
75     /// declare_lint! { pub LINT_2, ... }
76     /// declare_lint! { pub FORGOTTEN_LINT, ... }
77     /// // ...
78     /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
79     /// // missing FORGOTTEN_LINT
80     /// ```
81     pub LINT_WITHOUT_LINT_PASS,
82     internal,
83     "declaring a lint without associating it in a LintPass"
84 }
85
86 declare_clippy_lint! {
87     /// ### What it does
88     /// Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
89     /// variant of the function.
90     ///
91     /// ### Why is this bad?
92     /// The `utils::*` variants also add a link to the Clippy documentation to the
93     /// warning/error messages.
94     ///
95     /// ### Example
96     /// ```rust,ignore
97     /// cx.span_lint(LINT_NAME, "message");
98     /// ```
99     ///
100     /// Use instead:
101     /// ```rust,ignore
102     /// utils::span_lint(cx, LINT_NAME, "message");
103     /// ```
104     pub COMPILER_LINT_FUNCTIONS,
105     internal,
106     "usage of the lint functions of the compiler instead of the utils::* variant"
107 }
108
109 declare_clippy_lint! {
110     /// ### What it does
111     /// Checks for calls to `cx.outer().expn_data()` and suggests to use
112     /// the `cx.outer_expn_data()`
113     ///
114     /// ### Why is this bad?
115     /// `cx.outer_expn_data()` is faster and more concise.
116     ///
117     /// ### Example
118     /// ```rust,ignore
119     /// expr.span.ctxt().outer().expn_data()
120     /// ```
121     ///
122     /// Use instead:
123     /// ```rust,ignore
124     /// expr.span.ctxt().outer_expn_data()
125     /// ```
126     pub OUTER_EXPN_EXPN_DATA,
127     internal,
128     "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
129 }
130
131 declare_clippy_lint! {
132     /// ### What it does
133     /// Not an actual lint. This lint is only meant for testing our customized internal compiler
134     /// error message by calling `panic`.
135     ///
136     /// ### Why is this bad?
137     /// ICE in large quantities can damage your teeth
138     ///
139     /// ### Example
140     /// ```rust,ignore
141     /// 🍦🍦🍦🍦🍦
142     /// ```
143     pub PRODUCE_ICE,
144     internal,
145     "this message should not appear anywhere as we ICE before and don't emit the lint"
146 }
147
148 declare_clippy_lint! {
149     /// ### What it does
150     /// Checks for cases of an auto-generated lint without an updated description,
151     /// i.e. `default lint description`.
152     ///
153     /// ### Why is this bad?
154     /// Indicates that the lint is not finished.
155     ///
156     /// ### Example
157     /// ```rust,ignore
158     /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
159     /// ```
160     ///
161     /// Use instead:
162     /// ```rust,ignore
163     /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
164     /// ```
165     pub DEFAULT_LINT,
166     internal,
167     "found 'default lint description' in a lint declaration"
168 }
169
170 declare_clippy_lint! {
171     /// ### What it does
172     /// Lints `span_lint_and_then` function calls, where the
173     /// closure argument has only one statement and that statement is a method
174     /// call to `span_suggestion`, `span_help`, `span_note` (using the same
175     /// span), `help` or `note`.
176     ///
177     /// These usages of `span_lint_and_then` should be replaced with one of the
178     /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
179     /// `span_lint_and_note`.
180     ///
181     /// ### Why is this bad?
182     /// Using the wrapper `span_lint_and_*` functions, is more
183     /// convenient, readable and less error prone.
184     ///
185     /// ### Example
186     /// ```rust,ignore
187     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
188     ///     diag.span_suggestion(
189     ///         expr.span,
190     ///         help_msg,
191     ///         sugg.to_string(),
192     ///         Applicability::MachineApplicable,
193     ///     );
194     /// });
195     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
196     ///     diag.span_help(expr.span, help_msg);
197     /// });
198     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
199     ///     diag.help(help_msg);
200     /// });
201     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
202     ///     diag.span_note(expr.span, note_msg);
203     /// });
204     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
205     ///     diag.note(note_msg);
206     /// });
207     /// ```
208     ///
209     /// Use instead:
210     /// ```rust,ignore
211     /// span_lint_and_sugg(
212     ///     cx,
213     ///     TEST_LINT,
214     ///     expr.span,
215     ///     lint_msg,
216     ///     help_msg,
217     ///     sugg.to_string(),
218     ///     Applicability::MachineApplicable,
219     /// );
220     /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
221     /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
222     /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
223     /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
224     /// ```
225     pub COLLAPSIBLE_SPAN_LINT_CALLS,
226     internal,
227     "found collapsible `span_lint_and_then` calls"
228 }
229
230 declare_clippy_lint! {
231     /// ### What it does
232     /// Checks for usages of def paths when a diagnostic item or a `LangItem` could be used.
233     ///
234     /// ### Why is this bad?
235     /// The path for an item is subject to change and is less efficient to look up than a
236     /// diagnostic item or a `LangItem`.
237     ///
238     /// ### Example
239     /// ```rust,ignore
240     /// utils::match_type(cx, ty, &paths::VEC)
241     /// ```
242     ///
243     /// Use instead:
244     /// ```rust,ignore
245     /// utils::is_type_diagnostic_item(cx, ty, sym::Vec)
246     /// ```
247     pub UNNECESSARY_DEF_PATH,
248     internal,
249     "using a def path when a diagnostic item or a `LangItem` is available"
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     /// ```rust,ignore
275     /// let _ = sym!(f32);
276     /// ```
277     ///
278     /// Use instead:
279     /// ```rust,ignore
280     /// let _ = sym::f32;
281     /// ```
282     pub INTERNING_DEFINED_SYMBOL,
283     internal,
284     "interning a symbol that is pre-interned and defined as a constant"
285 }
286
287 declare_clippy_lint! {
288     /// ### What it does
289     /// Checks for unnecessary conversion from Symbol to a string.
290     ///
291     /// ### Why is this bad?
292     /// It's faster use symbols directly instead of strings.
293     ///
294     /// ### Example
295     /// ```rust,ignore
296     /// symbol.as_str() == "clippy";
297     /// ```
298     ///
299     /// Use instead:
300     /// ```rust,ignore
301     /// symbol == sym::clippy;
302     /// ```
303     pub UNNECESSARY_SYMBOL_STR,
304     internal,
305     "unnecessary conversion between Symbol and string"
306 }
307
308 declare_clippy_lint! {
309     /// Finds unidiomatic usage of `if_chain!`
310     pub IF_CHAIN_STYLE,
311     internal,
312     "non-idiomatic `if_chain!` usage"
313 }
314
315 declare_clippy_lint! {
316     /// ### What it does
317     /// Checks for invalid `clippy::version` attributes.
318     ///
319     /// Valid values are:
320     /// * "pre 1.29.0"
321     /// * any valid semantic version
322     pub INVALID_CLIPPY_VERSION_ATTRIBUTE,
323     internal,
324     "found an invalid `clippy::version` attribute"
325 }
326
327 declare_clippy_lint! {
328     /// ### What it does
329     /// Checks for declared clippy lints without the `clippy::version` attribute.
330     ///
331     pub MISSING_CLIPPY_VERSION_ATTRIBUTE,
332     internal,
333     "found clippy lint without `clippy::version` attribute"
334 }
335
336 declare_clippy_lint! {
337     /// ### What it does
338     /// Check that the `extract_msrv_attr!` macro is used, when a lint has a MSRV.
339     ///
340     pub MISSING_MSRV_ATTR_IMPL,
341     internal,
342     "checking if all necessary steps were taken when adding a MSRV to a lint"
343 }
344
345 declare_clippy_lint! {
346     /// ### What it does
347     /// Checks for cases of an auto-generated deprecated lint without an updated reason,
348     /// i.e. `"default deprecation note"`.
349     ///
350     /// ### Why is this bad?
351     /// Indicates that the documentation is incomplete.
352     ///
353     /// ### Example
354     /// ```rust,ignore
355     /// declare_deprecated_lint! {
356     ///     /// ### What it does
357     ///     /// Nothing. This lint has been deprecated.
358     ///     ///
359     ///     /// ### Deprecation reason
360     ///     /// TODO
361     ///     #[clippy::version = "1.63.0"]
362     ///     pub COOL_LINT,
363     ///     "default deprecation note"
364     /// }
365     /// ```
366     ///
367     /// Use instead:
368     /// ```rust,ignore
369     /// declare_deprecated_lint! {
370     ///     /// ### What it does
371     ///     /// Nothing. This lint has been deprecated.
372     ///     ///
373     ///     /// ### Deprecation reason
374     ///     /// This lint has been replaced by `cooler_lint`
375     ///     #[clippy::version = "1.63.0"]
376     ///     pub COOL_LINT,
377     ///     "this lint has been replaced by `cooler_lint`"
378     /// }
379     /// ```
380     pub DEFAULT_DEPRECATION_REASON,
381     internal,
382     "found 'default deprecation note' in a deprecated lint declaration"
383 }
384
385 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
386
387 impl EarlyLintPass for ClippyLintsInternal {
388     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &Crate) {
389         if let Some(utils) = krate.items.iter().find(|item| item.ident.name.as_str() == "utils") {
390             if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
391                 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
392                     if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
393                         let mut last_name: Option<&str> = None;
394                         for item in items {
395                             let name = item.ident.as_str();
396                             if let Some(last_name) = last_name {
397                                 if *last_name > *name {
398                                     span_lint(
399                                         cx,
400                                         CLIPPY_LINTS_INTERNAL,
401                                         item.span,
402                                         "this constant should be before the previous constant due to lexical \
403                                          ordering",
404                                     );
405                                 }
406                             }
407                             last_name = Some(name);
408                         }
409                     }
410                 }
411             }
412         }
413     }
414 }
415
416 #[derive(Clone, Debug, Default)]
417 pub struct LintWithoutLintPass {
418     declared_lints: FxHashMap<Symbol, Span>,
419     registered_lints: FxHashSet<Symbol>,
420 }
421
422 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS, INVALID_CLIPPY_VERSION_ATTRIBUTE, MISSING_CLIPPY_VERSION_ATTRIBUTE, DEFAULT_DEPRECATION_REASON]);
423
424 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
425     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
426         if is_lint_allowed(cx, DEFAULT_LINT, item.hir_id())
427             || is_lint_allowed(cx, DEFAULT_DEPRECATION_REASON, item.hir_id())
428         {
429             return;
430         }
431
432         if let hir::ItemKind::Static(ty, Mutability::Not, body_id) = item.kind {
433             let is_lint_ref_ty = is_lint_ref_type(cx, ty);
434             if is_deprecated_lint(cx, ty) || is_lint_ref_ty {
435                 check_invalid_clippy_version_attribute(cx, item);
436
437                 let expr = &cx.tcx.hir().body(body_id).value;
438                 let fields;
439                 if is_lint_ref_ty {
440                     if let ExprKind::AddrOf(_, _, inner_exp) = expr.kind
441                         && let ExprKind::Struct(_, struct_fields, _) = inner_exp.kind {
442                             fields = struct_fields;
443                     } else {
444                         return;
445                     }
446                 } else if let ExprKind::Struct(_, struct_fields, _) = expr.kind {
447                     fields = struct_fields;
448                 } else {
449                     return;
450                 }
451
452                 let field = fields
453                     .iter()
454                     .find(|f| f.ident.as_str() == "desc")
455                     .expect("lints must have a description field");
456
457                 if let ExprKind::Lit(Spanned {
458                     node: LitKind::Str(ref sym, _),
459                     ..
460                 }) = field.expr.kind
461                 {
462                     let sym_str = sym.as_str();
463                     if is_lint_ref_ty {
464                         if sym_str == "default lint description" {
465                             span_lint(
466                                 cx,
467                                 DEFAULT_LINT,
468                                 item.span,
469                                 &format!("the lint `{}` has the default lint description", item.ident.name),
470                             );
471                         }
472
473                         self.declared_lints.insert(item.ident.name, item.span);
474                     } else if sym_str == "default deprecation note" {
475                         span_lint(
476                             cx,
477                             DEFAULT_DEPRECATION_REASON,
478                             item.span,
479                             &format!("the lint `{}` has the default deprecation reason", item.ident.name),
480                         );
481                     }
482                 }
483             }
484         } else if let Some(macro_call) = root_macro_call_first_node(cx, item) {
485             if !matches!(
486                 cx.tcx.item_name(macro_call.def_id).as_str(),
487                 "impl_lint_pass" | "declare_lint_pass"
488             ) {
489                 return;
490             }
491             if let hir::ItemKind::Impl(hir::Impl {
492                 of_trait: None,
493                 items: impl_item_refs,
494                 ..
495             }) = item.kind
496             {
497                 let mut collector = LintCollector {
498                     output: &mut self.registered_lints,
499                     cx,
500                 };
501                 let body_id = cx.tcx.hir().body_owned_by(
502                     cx.tcx.hir().local_def_id(
503                         impl_item_refs
504                             .iter()
505                             .find(|iiref| iiref.ident.as_str() == "get_lints")
506                             .expect("LintPass needs to implement get_lints")
507                             .id
508                             .hir_id(),
509                     ),
510                 );
511                 collector.visit_expr(cx.tcx.hir().body(body_id).value);
512             }
513         }
514     }
515
516     fn check_crate_post(&mut self, cx: &LateContext<'tcx>) {
517         if is_lint_allowed(cx, LINT_WITHOUT_LINT_PASS, CRATE_HIR_ID) {
518             return;
519         }
520
521         for (lint_name, &lint_span) in &self.declared_lints {
522             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
523             // file points to "<rustc macros>".
524             // `compiletest-rs` thinks that's an error in a different file and
525             // just ignores it. This causes the test in compile-fail/lint_pass
526             // not able to capture the error.
527             // Therefore, we need to climb the macro expansion tree and find the
528             // actual span that invoked `declare_tool_lint!`:
529             let lint_span = lint_span.ctxt().outer_expn_data().call_site;
530
531             if !self.registered_lints.contains(lint_name) {
532                 span_lint(
533                     cx,
534                     LINT_WITHOUT_LINT_PASS,
535                     lint_span,
536                     &format!("the lint `{lint_name}` is not added to any `LintPass`"),
537                 );
538             }
539         }
540     }
541 }
542
543 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &hir::Ty<'_>) -> bool {
544     if let TyKind::Rptr(
545         _,
546         MutTy {
547             ty: inner,
548             mutbl: Mutability::Not,
549         },
550     ) = ty.kind
551     {
552         if let TyKind::Path(ref path) = inner.kind {
553             if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
554                 return match_def_path(cx, def_id, &paths::LINT);
555             }
556         }
557     }
558
559     false
560 }
561
562 fn check_invalid_clippy_version_attribute(cx: &LateContext<'_>, item: &'_ Item<'_>) {
563     if let Some(value) = extract_clippy_version_value(cx, item) {
564         // The `sym!` macro doesn't work as it only expects a single token.
565         // It's better to keep it this way and have a direct `Symbol::intern` call here.
566         if value == Symbol::intern("pre 1.29.0") {
567             return;
568         }
569
570         if RustcVersion::parse(value.as_str()).is_err() {
571             span_lint_and_help(
572                 cx,
573                 INVALID_CLIPPY_VERSION_ATTRIBUTE,
574                 item.span,
575                 "this item has an invalid `clippy::version` attribute",
576                 None,
577                 "please use a valid semantic version, see `doc/adding_lints.md`",
578             );
579         }
580     } else {
581         span_lint_and_help(
582             cx,
583             MISSING_CLIPPY_VERSION_ATTRIBUTE,
584             item.span,
585             "this lint is missing the `clippy::version` attribute or version value",
586             None,
587             "please use a `clippy::version` attribute, see `doc/adding_lints.md`",
588         );
589     }
590 }
591
592 /// This function extracts the version value of a `clippy::version` attribute if the given value has
593 /// one
594 fn extract_clippy_version_value(cx: &LateContext<'_>, item: &'_ Item<'_>) -> Option<Symbol> {
595     let attrs = cx.tcx.hir().attrs(item.hir_id());
596     attrs.iter().find_map(|attr| {
597         if_chain! {
598             // Identify attribute
599             if let ast::AttrKind::Normal(ref attr_kind) = &attr.kind;
600             if let [tool_name, attr_name] = &attr_kind.item.path.segments[..];
601             if tool_name.ident.name == sym::clippy;
602             if attr_name.ident.name == sym::version;
603             if let Some(version) = attr.value_str();
604             then {
605                 Some(version)
606             } else {
607                 None
608             }
609         }
610     })
611 }
612
613 struct LintCollector<'a, 'tcx> {
614     output: &'a mut FxHashSet<Symbol>,
615     cx: &'a LateContext<'tcx>,
616 }
617
618 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
619     type NestedFilter = nested_filter::All;
620
621     fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
622         if path.segments.len() == 1 {
623             self.output.insert(path.segments[0].ident.name);
624         }
625     }
626
627     fn nested_visit_map(&mut self) -> Self::Map {
628         self.cx.tcx.hir()
629     }
630 }
631
632 #[derive(Clone, Default)]
633 pub struct CompilerLintFunctions {
634     map: FxHashMap<&'static str, &'static str>,
635 }
636
637 impl CompilerLintFunctions {
638     #[must_use]
639     pub fn new() -> Self {
640         let mut map = FxHashMap::default();
641         map.insert("span_lint", "utils::span_lint");
642         map.insert("struct_span_lint", "utils::span_lint");
643         map.insert("lint", "utils::span_lint");
644         map.insert("span_lint_note", "utils::span_lint_and_note");
645         map.insert("span_lint_help", "utils::span_lint_and_help");
646         Self { map }
647     }
648 }
649
650 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
651
652 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
653     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
654         if is_lint_allowed(cx, COMPILER_LINT_FUNCTIONS, expr.hir_id) {
655             return;
656         }
657
658         if_chain! {
659             if let ExprKind::MethodCall(path, self_arg, _, _) = &expr.kind;
660             let fn_name = path.ident;
661             if let Some(sugg) = self.map.get(fn_name.as_str());
662             let ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
663             if match_type(cx, ty, &paths::EARLY_CONTEXT)
664                 || match_type(cx, ty, &paths::LATE_CONTEXT);
665             then {
666                 span_lint_and_help(
667                     cx,
668                     COMPILER_LINT_FUNCTIONS,
669                     path.ident.span,
670                     "usage of a compiler lint function",
671                     None,
672                     &format!("please use the Clippy variant of this function: `{sugg}`"),
673                 );
674             }
675         }
676     }
677 }
678
679 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
680
681 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
682     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
683         if is_lint_allowed(cx, OUTER_EXPN_EXPN_DATA, expr.hir_id) {
684             return;
685         }
686
687         let (method_names, arg_lists, spans) = method_calls(expr, 2);
688         let method_names: Vec<&str> = method_names.iter().map(Symbol::as_str).collect();
689         if_chain! {
690             if let ["expn_data", "outer_expn"] = method_names.as_slice();
691             let (self_arg, args)= arg_lists[1];
692             if args.is_empty();
693             let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
694             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
695             then {
696                 span_lint_and_sugg(
697                     cx,
698                     OUTER_EXPN_EXPN_DATA,
699                     spans[1].with_hi(expr.span.hi()),
700                     "usage of `outer_expn().expn_data()`",
701                     "try",
702                     "outer_expn_data()".to_string(),
703                     Applicability::MachineApplicable,
704                 );
705             }
706         }
707     }
708 }
709
710 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
711
712 impl EarlyLintPass for ProduceIce {
713     fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
714         assert!(!is_trigger_fn(fn_kind), "Would you like some help with that?");
715     }
716 }
717
718 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
719     match fn_kind {
720         FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
721         FnKind::Closure(..) => false,
722     }
723 }
724
725 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
726
727 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
728     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
729         if is_lint_allowed(cx, COLLAPSIBLE_SPAN_LINT_CALLS, expr.hir_id) {
730             return;
731         }
732
733         if_chain! {
734             if let ExprKind::Call(func, and_then_args) = expr.kind;
735             if is_expr_path_def_path(cx, func, &["clippy_utils", "diagnostics", "span_lint_and_then"]);
736             if and_then_args.len() == 5;
737             if let ExprKind::Closure(&Closure { body, .. }) = &and_then_args[4].kind;
738             let body = cx.tcx.hir().body(body);
739             let only_expr = peel_blocks_with_stmt(body.value);
740             if let ExprKind::MethodCall(ps, recv, span_call_args, _) = &only_expr.kind;
741             if let ExprKind::Path(..) = recv.kind;
742             then {
743                 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
744                 let mut sle = SpanlessEq::new(cx).deny_side_effects();
745                 match ps.ident.as_str() {
746                     "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => {
747                         suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
748                     },
749                     "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => {
750                         let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
751                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
752                     },
753                     "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[0]) => {
754                         let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
755                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
756                     },
757                     "help" => {
758                         let help_snippet = snippet(cx, span_call_args[0].span, r#""...""#);
759                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
760                     }
761                     "note" => {
762                         let note_snippet = snippet(cx, span_call_args[0].span, r#""...""#);
763                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
764                     }
765                     _  => (),
766                 }
767             }
768         }
769     }
770 }
771
772 struct AndThenSnippets<'a> {
773     cx: Cow<'a, str>,
774     lint: Cow<'a, str>,
775     span: Cow<'a, str>,
776     msg: Cow<'a, str>,
777 }
778
779 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
780     let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
781     let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
782     let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
783     let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
784
785     AndThenSnippets {
786         cx: cx_snippet,
787         lint: lint_snippet,
788         span: span_snippet,
789         msg: msg_snippet,
790     }
791 }
792
793 struct SpanSuggestionSnippets<'a> {
794     help: Cow<'a, str>,
795     sugg: Cow<'a, str>,
796     applicability: Cow<'a, str>,
797 }
798
799 fn span_suggestion_snippets<'a, 'hir>(
800     cx: &LateContext<'_>,
801     span_call_args: &'hir [Expr<'hir>],
802 ) -> SpanSuggestionSnippets<'a> {
803     let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
804     let sugg_snippet = snippet(cx, span_call_args[2].span, "..");
805     let applicability_snippet = snippet(cx, span_call_args[3].span, "Applicability::MachineApplicable");
806
807     SpanSuggestionSnippets {
808         help: help_snippet,
809         sugg: sugg_snippet,
810         applicability: applicability_snippet,
811     }
812 }
813
814 fn suggest_suggestion(
815     cx: &LateContext<'_>,
816     expr: &Expr<'_>,
817     and_then_snippets: &AndThenSnippets<'_>,
818     span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
819 ) {
820     span_lint_and_sugg(
821         cx,
822         COLLAPSIBLE_SPAN_LINT_CALLS,
823         expr.span,
824         "this call is collapsible",
825         "collapse into",
826         format!(
827             "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
828             and_then_snippets.cx,
829             and_then_snippets.lint,
830             and_then_snippets.span,
831             and_then_snippets.msg,
832             span_suggestion_snippets.help,
833             span_suggestion_snippets.sugg,
834             span_suggestion_snippets.applicability
835         ),
836         Applicability::MachineApplicable,
837     );
838 }
839
840 fn suggest_help(
841     cx: &LateContext<'_>,
842     expr: &Expr<'_>,
843     and_then_snippets: &AndThenSnippets<'_>,
844     help: &str,
845     with_span: bool,
846 ) {
847     let option_span = if with_span {
848         format!("Some({})", and_then_snippets.span)
849     } else {
850         "None".to_string()
851     };
852
853     span_lint_and_sugg(
854         cx,
855         COLLAPSIBLE_SPAN_LINT_CALLS,
856         expr.span,
857         "this call is collapsible",
858         "collapse into",
859         format!(
860             "span_lint_and_help({}, {}, {}, {}, {}, {help})",
861             and_then_snippets.cx, and_then_snippets.lint, and_then_snippets.span, and_then_snippets.msg, &option_span,
862         ),
863         Applicability::MachineApplicable,
864     );
865 }
866
867 fn suggest_note(
868     cx: &LateContext<'_>,
869     expr: &Expr<'_>,
870     and_then_snippets: &AndThenSnippets<'_>,
871     note: &str,
872     with_span: bool,
873 ) {
874     let note_span = if with_span {
875         format!("Some({})", and_then_snippets.span)
876     } else {
877         "None".to_string()
878     };
879
880     span_lint_and_sugg(
881         cx,
882         COLLAPSIBLE_SPAN_LINT_CALLS,
883         expr.span,
884         "this call is collapsible",
885         "collapse into",
886         format!(
887             "span_lint_and_note({}, {}, {}, {}, {note_span}, {note})",
888             and_then_snippets.cx, and_then_snippets.lint, and_then_snippets.span, and_then_snippets.msg,
889         ),
890         Applicability::MachineApplicable,
891     );
892 }
893
894 declare_lint_pass!(UnnecessaryDefPath => [UNNECESSARY_DEF_PATH]);
895
896 #[allow(clippy::too_many_lines)]
897 impl<'tcx> LateLintPass<'tcx> for UnnecessaryDefPath {
898     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
899         enum Item {
900             LangItem(Symbol),
901             DiagnosticItem(Symbol),
902         }
903         static PATHS: &[&[&str]] = &[
904             &["clippy_utils", "match_def_path"],
905             &["clippy_utils", "match_trait_method"],
906             &["clippy_utils", "ty", "match_type"],
907             &["clippy_utils", "is_expr_path_def_path"],
908         ];
909
910         if is_lint_allowed(cx, UNNECESSARY_DEF_PATH, expr.hir_id) {
911             return;
912         }
913
914         if_chain! {
915             if let ExprKind::Call(func, [cx_arg, def_arg, args@..]) = expr.kind;
916             if let ExprKind::Path(path) = &func.kind;
917             if let Some(id) = cx.qpath_res(path, func.hir_id).opt_def_id();
918             if let Some(which_path) = match_any_def_paths(cx, id, PATHS);
919             let item_arg = if which_path == 4 { &args[1] } else { &args[0] };
920             // Extract the path to the matched type
921             if let Some(segments) = path_to_matched_type(cx, item_arg);
922             let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
923             if let Some(def_id) = def_path_res(cx, &segments[..], None).opt_def_id();
924             then {
925                 // def_path_res will match field names before anything else, but for this we want to match
926                 // inherent functions first.
927                 let def_id = if cx.tcx.def_kind(def_id) == DefKind::Field {
928                     let method_name = *segments.last().unwrap();
929                     cx.tcx.def_key(def_id).parent
930                         .and_then(|parent_idx|
931                             cx.tcx.inherent_impls(DefId { index: parent_idx, krate: def_id.krate }).iter()
932                                 .find_map(|impl_id| cx.tcx.associated_items(*impl_id)
933                                     .find_by_name_and_kind(
934                                         cx.tcx,
935                                         Ident::from_str(method_name),
936                                         AssocKind::Fn,
937                                         *impl_id,
938                                     )
939                                 )
940                         )
941                         .map_or(def_id, |item| item.def_id)
942                 } else {
943                     def_id
944                 };
945
946                 // Check if the target item is a diagnostic item or LangItem.
947                 let (msg, item) = if let Some(item_name)
948                     = cx.tcx.diagnostic_items(def_id.krate).id_to_name.get(&def_id)
949                 {
950                     (
951                         "use of a def path to a diagnostic item",
952                         Item::DiagnosticItem(*item_name),
953                     )
954                 } else if let Some(lang_item) = cx.tcx.lang_items().items().iter().position(|id| *id == Some(def_id)) {
955                     let lang_items = def_path_res(cx, &["rustc_hir", "lang_items", "LangItem"], Some(Namespace::TypeNS)).def_id();
956                     let item_name = cx.tcx.adt_def(lang_items).variants().iter().nth(lang_item).unwrap().name;
957                     (
958                         "use of a def path to a `LangItem`",
959                         Item::LangItem(item_name),
960                     )
961                 } else {
962                     return;
963                 };
964
965                 let has_ctor = match cx.tcx.def_kind(def_id) {
966                     DefKind::Struct => {
967                         let variant = cx.tcx.adt_def(def_id).non_enum_variant();
968                         variant.ctor_def_id.is_some() && variant.fields.iter().all(|f| f.vis.is_public())
969                     }
970                     DefKind::Variant => {
971                         let variant = cx.tcx.adt_def(cx.tcx.parent(def_id)).variant_with_id(def_id);
972                         variant.ctor_def_id.is_some() && variant.fields.iter().all(|f| f.vis.is_public())
973                     }
974                     _ => false,
975                 };
976
977                 let mut app = Applicability::MachineApplicable;
978                 let cx_snip = snippet_with_applicability(cx, cx_arg.span, "..", &mut app);
979                 let def_snip = snippet_with_applicability(cx, def_arg.span, "..", &mut app);
980                 let (sugg, with_note) = match (which_path, item) {
981                     // match_def_path
982                     (0, Item::DiagnosticItem(item)) =>
983                         (format!("{cx_snip}.tcx.is_diagnostic_item(sym::{item}, {def_snip})"), has_ctor),
984                     (0, Item::LangItem(item)) => (
985                         format!("{cx_snip}.tcx.lang_items().require(LangItem::{item}).ok() == Some({def_snip})"),
986                         has_ctor
987                     ),
988                     // match_trait_method
989                     (1, Item::DiagnosticItem(item)) =>
990                         (format!("is_trait_method({cx_snip}, {def_snip}, sym::{item})"), false),
991                     // match_type
992                     (2, Item::DiagnosticItem(item)) =>
993                         (format!("is_type_diagnostic_item({cx_snip}, {def_snip}, sym::{item})"), false),
994                     (2, Item::LangItem(item)) =>
995                         (format!("is_type_lang_item({cx_snip}, {def_snip}, LangItem::{item})"), false),
996                     // is_expr_path_def_path
997                     (3, Item::DiagnosticItem(item)) if has_ctor => (
998                         format!(
999                             "is_res_diag_ctor({cx_snip}, path_res({cx_snip}, {def_snip}), sym::{item})",
1000                         ),
1001                         false,
1002                     ),
1003                     (3, Item::LangItem(item)) if has_ctor => (
1004                         format!(
1005                             "is_res_lang_ctor({cx_snip}, path_res({cx_snip}, {def_snip}), LangItem::{item})",
1006                         ),
1007                         false,
1008                     ),
1009                     (3, Item::DiagnosticItem(item)) =>
1010                         (format!("is_path_diagnostic_item({cx_snip}, {def_snip}, sym::{item})"), false),
1011                     (3, Item::LangItem(item)) => (
1012                         format!(
1013                             "path_res({cx_snip}, {def_snip}).opt_def_id()\
1014                                 .map_or(false, |id| {cx_snip}.tcx.lang_items().require(LangItem::{item}).ok() == Some(id))",
1015                         ),
1016                         false,
1017                     ),
1018                     _ => return,
1019                 };
1020
1021                 span_lint_and_then(
1022                     cx,
1023                     UNNECESSARY_DEF_PATH,
1024                     expr.span,
1025                     msg,
1026                     |diag| {
1027                         diag.span_suggestion(expr.span, "try", sugg, app);
1028                         if with_note {
1029                             diag.help(
1030                                 "if this `DefId` came from a constructor expression or pattern then the \
1031                                     parent `DefId` should be used instead"
1032                             );
1033                         }
1034                     },
1035                 );
1036             }
1037         }
1038     }
1039 }
1040
1041 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<String>> {
1042     match peel_hir_expr_refs(expr).0.kind {
1043         ExprKind::Path(ref qpath) => match cx.qpath_res(qpath, expr.hir_id) {
1044             Res::Local(hir_id) => {
1045                 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
1046                 if let Some(Node::Local(Local { init: Some(init), .. })) = cx.tcx.hir().find(parent_id) {
1047                     path_to_matched_type(cx, init)
1048                 } else {
1049                     None
1050                 }
1051             },
1052             Res::Def(DefKind::Static(_), def_id) => read_mir_alloc_def_path(
1053                 cx,
1054                 cx.tcx.eval_static_initializer(def_id).ok()?.inner(),
1055                 cx.tcx.type_of(def_id),
1056             ),
1057             Res::Def(DefKind::Const, def_id) => match cx.tcx.const_eval_poly(def_id).ok()? {
1058                 ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => {
1059                     read_mir_alloc_def_path(cx, alloc.inner(), cx.tcx.type_of(def_id))
1060                 },
1061                 _ => None,
1062             },
1063             _ => None,
1064         },
1065         ExprKind::Array(exprs) => exprs
1066             .iter()
1067             .map(|expr| {
1068                 if let ExprKind::Lit(lit) = &expr.kind {
1069                     if let LitKind::Str(sym, _) = lit.node {
1070                         return Some((*sym.as_str()).to_owned());
1071                     }
1072                 }
1073
1074                 None
1075             })
1076             .collect(),
1077         _ => None,
1078     }
1079 }
1080
1081 fn read_mir_alloc_def_path<'tcx>(cx: &LateContext<'tcx>, alloc: &'tcx Allocation, ty: Ty<'_>) -> Option<Vec<String>> {
1082     let (alloc, ty) = if let ty::Ref(_, ty, Mutability::Not) = *ty.kind() {
1083         let &alloc = alloc.provenance().values().next()?;
1084         if let GlobalAlloc::Memory(alloc) = cx.tcx.global_alloc(alloc) {
1085             (alloc.inner(), ty)
1086         } else {
1087             return None;
1088         }
1089     } else {
1090         (alloc, ty)
1091     };
1092
1093     if let ty::Array(ty, _) | ty::Slice(ty) = *ty.kind()
1094         && let ty::Ref(_, ty, Mutability::Not) = *ty.kind()
1095         && ty.is_str()
1096     {
1097         alloc
1098             .provenance()
1099             .values()
1100             .map(|&alloc| {
1101                 if let GlobalAlloc::Memory(alloc) = cx.tcx.global_alloc(alloc) {
1102                     let alloc = alloc.inner();
1103                     str::from_utf8(alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()))
1104                         .ok().map(ToOwned::to_owned)
1105                 } else {
1106                     None
1107                 }
1108             })
1109             .collect()
1110     } else {
1111         None
1112     }
1113 }
1114
1115 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
1116 // module.  That's all it does and all it needs to do.
1117 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
1118     if def_path_res(cx, path, None) != Res::Err {
1119         return true;
1120     }
1121
1122     // Some implementations can't be found by `path_to_res`, particularly inherent
1123     // implementations of native types. Check lang items.
1124     let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
1125     let lang_items = cx.tcx.lang_items();
1126     // This list isn't complete, but good enough for our current list of paths.
1127     let incoherent_impls = [
1128         SimplifiedTypeGen::FloatSimplifiedType(FloatTy::F32),
1129         SimplifiedTypeGen::FloatSimplifiedType(FloatTy::F64),
1130         SimplifiedTypeGen::SliceSimplifiedType,
1131         SimplifiedTypeGen::StrSimplifiedType,
1132     ]
1133     .iter()
1134     .flat_map(|&ty| cx.tcx.incoherent_impls(ty));
1135     for item_def_id in lang_items.items().iter().flatten().chain(incoherent_impls) {
1136         let lang_item_path = cx.get_def_path(*item_def_id);
1137         if path_syms.starts_with(&lang_item_path) {
1138             if let [item] = &path_syms[lang_item_path.len()..] {
1139                 if matches!(
1140                     cx.tcx.def_kind(*item_def_id),
1141                     DefKind::Mod | DefKind::Enum | DefKind::Trait
1142                 ) {
1143                     for child in cx.tcx.module_children(*item_def_id) {
1144                         if child.ident.name == *item {
1145                             return true;
1146                         }
1147                     }
1148                 } else {
1149                     for child in cx.tcx.associated_item_def_ids(*item_def_id) {
1150                         if cx.tcx.item_name(*child) == *item {
1151                             return true;
1152                         }
1153                     }
1154                 }
1155             }
1156         }
1157     }
1158
1159     false
1160 }
1161
1162 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
1163
1164 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
1165     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
1166         let local_def_id = &cx.tcx.parent_module(item.hir_id());
1167         let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
1168         if_chain! {
1169             if mod_name.as_str() == "paths";
1170             if let hir::ItemKind::Const(ty, body_id) = item.kind;
1171             let ty = hir_ty_to_ty(cx.tcx, ty);
1172             if let ty::Array(el_ty, _) = &ty.kind();
1173             if let ty::Ref(_, el_ty, _) = &el_ty.kind();
1174             if el_ty.is_str();
1175             let body = cx.tcx.hir().body(body_id);
1176             let typeck_results = cx.tcx.typeck_body(body_id);
1177             if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, body.value);
1178             let path: Vec<&str> = path.iter().map(|x| {
1179                     if let Constant::Str(s) = x {
1180                         s.as_str()
1181                     } else {
1182                         // We checked the type of the constant above
1183                         unreachable!()
1184                     }
1185                 }).collect();
1186             if !check_path(cx, &path[..]);
1187             then {
1188                 span_lint(cx, INVALID_PATHS, item.span, "invalid path");
1189             }
1190         }
1191     }
1192 }
1193
1194 #[derive(Default)]
1195 pub struct InterningDefinedSymbol {
1196     // Maps the symbol value to the constant DefId.
1197     symbol_map: FxHashMap<u32, DefId>,
1198 }
1199
1200 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
1201
1202 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
1203     fn check_crate(&mut self, cx: &LateContext<'_>) {
1204         if !self.symbol_map.is_empty() {
1205             return;
1206         }
1207
1208         for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
1209             if let Some(def_id) = def_path_res(cx, module, None).opt_def_id() {
1210                 for item in cx.tcx.module_children(def_id).iter() {
1211                     if_chain! {
1212                         if let Res::Def(DefKind::Const, item_def_id) = item.res;
1213                         let ty = cx.tcx.type_of(item_def_id);
1214                         if match_type(cx, ty, &paths::SYMBOL);
1215                         if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
1216                         if let Ok(value) = value.to_u32();
1217                         then {
1218                             self.symbol_map.insert(value, item_def_id);
1219                         }
1220                     }
1221                 }
1222             }
1223         }
1224     }
1225
1226     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1227         if_chain! {
1228             if let ExprKind::Call(func, [arg]) = &expr.kind;
1229             if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
1230             if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
1231             if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
1232             let value = Symbol::intern(&arg).as_u32();
1233             if let Some(&def_id) = self.symbol_map.get(&value);
1234             then {
1235                 span_lint_and_sugg(
1236                     cx,
1237                     INTERNING_DEFINED_SYMBOL,
1238                     is_expn_of(expr.span, "sym").unwrap_or(expr.span),
1239                     "interning a defined symbol",
1240                     "try",
1241                     cx.tcx.def_path_str(def_id),
1242                     Applicability::MachineApplicable,
1243                 );
1244             }
1245         }
1246         if let ExprKind::Binary(op, left, right) = expr.kind {
1247             if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
1248                 let data = [
1249                     (left, self.symbol_str_expr(left, cx)),
1250                     (right, self.symbol_str_expr(right, cx)),
1251                 ];
1252                 match data {
1253                     // both operands are a symbol string
1254                     [(_, Some(left)), (_, Some(right))] => {
1255                         span_lint_and_sugg(
1256                             cx,
1257                             UNNECESSARY_SYMBOL_STR,
1258                             expr.span,
1259                             "unnecessary `Symbol` to string conversion",
1260                             "try",
1261                             format!(
1262                                 "{} {} {}",
1263                                 left.as_symbol_snippet(cx),
1264                                 op.node.as_str(),
1265                                 right.as_symbol_snippet(cx),
1266                             ),
1267                             Applicability::MachineApplicable,
1268                         );
1269                     },
1270                     // one of the operands is a symbol string
1271                     [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
1272                         // creating an owned string for comparison
1273                         if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
1274                             span_lint_and_sugg(
1275                                 cx,
1276                                 UNNECESSARY_SYMBOL_STR,
1277                                 expr.span,
1278                                 "unnecessary string allocation",
1279                                 "try",
1280                                 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
1281                                 Applicability::MachineApplicable,
1282                             );
1283                         }
1284                     },
1285                     // nothing found
1286                     [(_, None), (_, None)] => {},
1287                 }
1288             }
1289         }
1290     }
1291 }
1292
1293 impl InterningDefinedSymbol {
1294     fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
1295         static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
1296         static SYMBOL_STR_PATHS: &[&[&str]] = &[
1297             &paths::SYMBOL_AS_STR,
1298             &paths::SYMBOL_TO_IDENT_STRING,
1299             &paths::TO_STRING_METHOD,
1300         ];
1301         let call = if_chain! {
1302             if let ExprKind::AddrOf(_, _, e) = expr.kind;
1303             if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
1304             then { e } else { expr }
1305         };
1306         if_chain! {
1307             // is a method call
1308             if let ExprKind::MethodCall(_, item, [], _) = call.kind;
1309             if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1310             let ty = cx.typeck_results().expr_ty(item);
1311             // ...on either an Ident or a Symbol
1312             if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1313                 Some(false)
1314             } else if match_type(cx, ty, &paths::IDENT) {
1315                 Some(true)
1316             } else {
1317                 None
1318             };
1319             // ...which converts it to a string
1320             let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1321             if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1322             then {
1323                 let is_to_owned = path.last().unwrap().ends_with("string");
1324                 return Some(SymbolStrExpr::Expr {
1325                     item,
1326                     is_ident,
1327                     is_to_owned,
1328                 });
1329             }
1330         }
1331         // is a string constant
1332         if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1333             let value = Symbol::intern(&s).as_u32();
1334             // ...which matches a symbol constant
1335             if let Some(&def_id) = self.symbol_map.get(&value) {
1336                 return Some(SymbolStrExpr::Const(def_id));
1337             }
1338         }
1339         None
1340     }
1341 }
1342
1343 enum SymbolStrExpr<'tcx> {
1344     /// a string constant with a corresponding symbol constant
1345     Const(DefId),
1346     /// a "symbol to string" expression like `symbol.as_str()`
1347     Expr {
1348         /// part that evaluates to `Symbol` or `Ident`
1349         item: &'tcx Expr<'tcx>,
1350         is_ident: bool,
1351         /// whether an owned `String` is created like `to_ident_string()`
1352         is_to_owned: bool,
1353     },
1354 }
1355
1356 impl<'tcx> SymbolStrExpr<'tcx> {
1357     /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1358     fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1359         match *self {
1360             Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1361             Self::Expr { item, is_ident, .. } => {
1362                 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1363                 if is_ident {
1364                     // get `Ident.name`
1365                     snip.to_mut().push_str(".name");
1366                 }
1367                 snip
1368             },
1369         }
1370     }
1371 }
1372
1373 declare_lint_pass!(IfChainStyle => [IF_CHAIN_STYLE]);
1374
1375 impl<'tcx> LateLintPass<'tcx> for IfChainStyle {
1376     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
1377         let (local, after, if_chain_span) = if_chain! {
1378             if let [Stmt { kind: StmtKind::Local(local), .. }, after @ ..] = block.stmts;
1379             if let Some(if_chain_span) = is_expn_of(block.span, "if_chain");
1380             then { (local, after, if_chain_span) } else { return }
1381         };
1382         if is_first_if_chain_expr(cx, block.hir_id, if_chain_span) {
1383             span_lint(
1384                 cx,
1385                 IF_CHAIN_STYLE,
1386                 if_chain_local_span(cx, local, if_chain_span),
1387                 "`let` expression should be above the `if_chain!`",
1388             );
1389         } else if local.span.ctxt() == block.span.ctxt() && is_if_chain_then(after, block.expr, if_chain_span) {
1390             span_lint(
1391                 cx,
1392                 IF_CHAIN_STYLE,
1393                 if_chain_local_span(cx, local, if_chain_span),
1394                 "`let` expression should be inside `then { .. }`",
1395             );
1396         }
1397     }
1398
1399     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1400         let (cond, then, els) = if let Some(higher::IfOrIfLet { cond, r#else, then }) = higher::IfOrIfLet::hir(expr) {
1401             (cond, then, r#else.is_some())
1402         } else {
1403             return;
1404         };
1405         let then_block = match then.kind {
1406             ExprKind::Block(block, _) => block,
1407             _ => return,
1408         };
1409         let if_chain_span = is_expn_of(expr.span, "if_chain");
1410         if !els {
1411             check_nested_if_chains(cx, expr, then_block, if_chain_span);
1412         }
1413         let if_chain_span = match if_chain_span {
1414             None => return,
1415             Some(span) => span,
1416         };
1417         // check for `if a && b;`
1418         if_chain! {
1419             if let ExprKind::Binary(op, _, _) = cond.kind;
1420             if op.node == BinOpKind::And;
1421             if cx.sess().source_map().is_multiline(cond.span);
1422             then {
1423                 span_lint(cx, IF_CHAIN_STYLE, cond.span, "`if a && b;` should be `if a; if b;`");
1424             }
1425         }
1426         if is_first_if_chain_expr(cx, expr.hir_id, if_chain_span)
1427             && is_if_chain_then(then_block.stmts, then_block.expr, if_chain_span)
1428         {
1429             span_lint(cx, IF_CHAIN_STYLE, expr.span, "`if_chain!` only has one `if`");
1430         }
1431     }
1432 }
1433
1434 fn check_nested_if_chains(
1435     cx: &LateContext<'_>,
1436     if_expr: &Expr<'_>,
1437     then_block: &Block<'_>,
1438     if_chain_span: Option<Span>,
1439 ) {
1440     #[rustfmt::skip]
1441     let (head, tail) = match *then_block {
1442         Block { stmts, expr: Some(tail), .. } => (stmts, tail),
1443         Block {
1444             stmts: &[
1445                 ref head @ ..,
1446                 Stmt { kind: StmtKind::Expr(tail) | StmtKind::Semi(tail), .. }
1447             ],
1448             ..
1449         } => (head, tail),
1450         _ => return,
1451     };
1452     if_chain! {
1453         if let Some(higher::IfOrIfLet { r#else: None, .. }) = higher::IfOrIfLet::hir(tail);
1454         let sm = cx.sess().source_map();
1455         if head
1456             .iter()
1457             .all(|stmt| matches!(stmt.kind, StmtKind::Local(..)) && !sm.is_multiline(stmt.span));
1458         if if_chain_span.is_some() || !is_else_clause(cx.tcx, if_expr);
1459         then {} else { return }
1460     }
1461     let (span, msg) = match (if_chain_span, is_expn_of(tail.span, "if_chain")) {
1462         (None, Some(_)) => (if_expr.span, "this `if` can be part of the inner `if_chain!`"),
1463         (Some(_), None) => (tail.span, "this `if` can be part of the outer `if_chain!`"),
1464         (Some(a), Some(b)) if a != b => (b, "this `if_chain!` can be merged with the outer `if_chain!`"),
1465         _ => return,
1466     };
1467     span_lint_and_then(cx, IF_CHAIN_STYLE, span, msg, |diag| {
1468         let (span, msg) = match head {
1469             [] => return,
1470             [stmt] => (stmt.span, "this `let` statement can also be in the `if_chain!`"),
1471             [a, .., b] => (
1472                 a.span.to(b.span),
1473                 "these `let` statements can also be in the `if_chain!`",
1474             ),
1475         };
1476         diag.span_help(span, msg);
1477     });
1478 }
1479
1480 fn is_first_if_chain_expr(cx: &LateContext<'_>, hir_id: HirId, if_chain_span: Span) -> bool {
1481     cx.tcx
1482         .hir()
1483         .parent_iter(hir_id)
1484         .find(|(_, node)| {
1485             #[rustfmt::skip]
1486             !matches!(node, Node::Expr(Expr { kind: ExprKind::Block(..), .. }) | Node::Stmt(_))
1487         })
1488         .map_or(false, |(id, _)| {
1489             is_expn_of(cx.tcx.hir().span(id), "if_chain") != Some(if_chain_span)
1490         })
1491 }
1492
1493 /// Checks a trailing slice of statements and expression of a `Block` to see if they are part
1494 /// of the `then {..}` portion of an `if_chain!`
1495 fn is_if_chain_then(stmts: &[Stmt<'_>], expr: Option<&Expr<'_>>, if_chain_span: Span) -> bool {
1496     let span = if let [stmt, ..] = stmts {
1497         stmt.span
1498     } else if let Some(expr) = expr {
1499         expr.span
1500     } else {
1501         // empty `then {}`
1502         return true;
1503     };
1504     is_expn_of(span, "if_chain").map_or(true, |span| span != if_chain_span)
1505 }
1506
1507 /// Creates a `Span` for `let x = ..;` in an `if_chain!` call.
1508 fn if_chain_local_span(cx: &LateContext<'_>, local: &Local<'_>, if_chain_span: Span) -> Span {
1509     let mut span = local.pat.span;
1510     if let Some(init) = local.init {
1511         span = span.to(init.span);
1512     }
1513     span.adjust(if_chain_span.ctxt().outer_expn());
1514     let sm = cx.sess().source_map();
1515     let span = sm.span_extend_to_prev_str(span, "let", false, true).unwrap_or(span);
1516     let span = sm.span_extend_to_next_char(span, ';', false);
1517     Span::new(
1518         span.lo() - BytePos(3),
1519         span.hi() + BytePos(1),
1520         span.ctxt(),
1521         span.parent(),
1522     )
1523 }
1524
1525 declare_lint_pass!(MsrvAttrImpl => [MISSING_MSRV_ATTR_IMPL]);
1526
1527 impl LateLintPass<'_> for MsrvAttrImpl {
1528     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1529         if_chain! {
1530             if let hir::ItemKind::Impl(hir::Impl {
1531                 of_trait: Some(lint_pass_trait_ref),
1532                 self_ty,
1533                 items,
1534                 ..
1535             }) = &item.kind;
1536             if let Some(lint_pass_trait_def_id) = lint_pass_trait_ref.trait_def_id();
1537             let is_late_pass = match_def_path(cx, lint_pass_trait_def_id, &paths::LATE_LINT_PASS);
1538             if is_late_pass || match_def_path(cx, lint_pass_trait_def_id, &paths::EARLY_LINT_PASS);
1539             let self_ty = hir_ty_to_ty(cx.tcx, self_ty);
1540             if let ty::Adt(self_ty_def, _) = self_ty.kind();
1541             if self_ty_def.is_struct();
1542             if self_ty_def.all_fields().any(|f| {
1543                 cx.tcx
1544                     .type_of(f.did)
1545                     .walk()
1546                     .filter(|t| matches!(t.unpack(), GenericArgKind::Type(_)))
1547                     .any(|t| match_type(cx, t.expect_ty(), &paths::RUSTC_VERSION))
1548             });
1549             if !items.iter().any(|item| item.ident.name == sym!(enter_lint_attrs));
1550             then {
1551                 let context = if is_late_pass { "LateContext" } else { "EarlyContext" };
1552                 let lint_pass = if is_late_pass { "LateLintPass" } else { "EarlyLintPass" };
1553                 let span = cx.sess().source_map().span_through_char(item.span, '{');
1554                 span_lint_and_sugg(
1555                     cx,
1556                     MISSING_MSRV_ATTR_IMPL,
1557                     span,
1558                     &format!("`extract_msrv_attr!` macro missing from `{lint_pass}` implementation"),
1559                     &format!("add `extract_msrv_attr!({context})` to the `{lint_pass}` implementation"),
1560                     format!("{}\n    extract_msrv_attr!({context});", snippet(cx, span, "..")),
1561                     Applicability::MachineApplicable,
1562                 );
1563             }
1564         }
1565     }
1566 }