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;
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,
11 use if_chain::if_chain;
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;
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;
23 BinOpKind, Block, Closure, Expr, ExprKind, HirId, Item, Local, MutTy, Mutability, Node, Path, Stmt, StmtKind,
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,
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};
39 use std::borrow::{Borrow, Cow};
42 #[cfg(feature = "internal")]
43 pub mod metadata_collector;
45 declare_clippy_lint! {
47 /// Checks for various things we like to keep tidy in clippy.
49 /// ### Why is this bad?
50 /// We like to pretend we're an example of tidy code.
53 /// Wrong ordering of the util::paths constants.
54 pub CLIPPY_LINTS_INTERNAL,
56 "various things that will negatively affect your clippy experience"
59 declare_clippy_lint! {
61 /// Ensures every lint is associated to a `LintPass`.
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.
68 /// ### Known problems
69 /// Only checks for lints associated using the
70 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
74 /// declare_lint! { pub LINT_1, ... }
75 /// declare_lint! { pub LINT_2, ... }
76 /// declare_lint! { pub FORGOTTEN_LINT, ... }
78 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
79 /// // missing FORGOTTEN_LINT
81 pub LINT_WITHOUT_LINT_PASS,
83 "declaring a lint without associating it in a LintPass"
86 declare_clippy_lint! {
88 /// Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
89 /// variant of the function.
91 /// ### Why is this bad?
92 /// The `utils::*` variants also add a link to the Clippy documentation to the
93 /// warning/error messages.
97 /// cx.span_lint(LINT_NAME, "message");
102 /// utils::span_lint(cx, LINT_NAME, "message");
104 pub COMPILER_LINT_FUNCTIONS,
106 "usage of the lint functions of the compiler instead of the utils::* variant"
109 declare_clippy_lint! {
111 /// Checks for calls to `cx.outer().expn_data()` and suggests to use
112 /// the `cx.outer_expn_data()`
114 /// ### Why is this bad?
115 /// `cx.outer_expn_data()` is faster and more concise.
119 /// expr.span.ctxt().outer().expn_data()
124 /// expr.span.ctxt().outer_expn_data()
126 pub OUTER_EXPN_EXPN_DATA,
128 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
131 declare_clippy_lint! {
133 /// Not an actual lint. This lint is only meant for testing our customized internal compiler
134 /// error message by calling `panic`.
136 /// ### Why is this bad?
137 /// ICE in large quantities can damage your teeth
145 "this message should not appear anywhere as we ICE before and don't emit the lint"
148 declare_clippy_lint! {
150 /// Checks for cases of an auto-generated lint without an updated description,
151 /// i.e. `default lint description`.
153 /// ### Why is this bad?
154 /// Indicates that the lint is not finished.
158 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
163 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
167 "found 'default lint description' in a lint declaration"
170 declare_clippy_lint! {
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`.
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`.
181 /// ### Why is this bad?
182 /// Using the wrapper `span_lint_and_*` functions, is more
183 /// convenient, readable and less error prone.
187 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
188 /// diag.span_suggestion(
191 /// sugg.to_string(),
192 /// Applicability::MachineApplicable,
195 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
196 /// diag.span_help(expr.span, help_msg);
198 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
199 /// diag.help(help_msg);
201 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
202 /// diag.span_note(expr.span, note_msg);
204 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
205 /// diag.note(note_msg);
211 /// span_lint_and_sugg(
217 /// sugg.to_string(),
218 /// Applicability::MachineApplicable,
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);
225 pub COLLAPSIBLE_SPAN_LINT_CALLS,
227 "found collapsible `span_lint_and_then` calls"
230 declare_clippy_lint! {
232 /// Checks for usages of def paths when a diagnostic item or a `LangItem` could be used.
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`.
240 /// utils::match_type(cx, ty, &paths::VEC)
245 /// utils::is_type_diagnostic_item(cx, ty, sym::Vec)
247 pub UNNECESSARY_DEF_PATH,
249 "using a def path when a diagnostic item or a `LangItem` is available"
252 declare_clippy_lint! {
254 /// Checks the paths module for invalid paths.
256 /// ### Why is this bad?
257 /// It indicates a bug in the code.
266 declare_clippy_lint! {
268 /// Checks for interning symbols that have already been pre-interned and defined as constants.
270 /// ### Why is this bad?
271 /// It's faster and easier to use the symbol constant.
275 /// let _ = sym!(f32);
280 /// let _ = sym::f32;
282 pub INTERNING_DEFINED_SYMBOL,
284 "interning a symbol that is pre-interned and defined as a constant"
287 declare_clippy_lint! {
289 /// Checks for unnecessary conversion from Symbol to a string.
291 /// ### Why is this bad?
292 /// It's faster use symbols directly instead of strings.
296 /// symbol.as_str() == "clippy";
301 /// symbol == sym::clippy;
303 pub UNNECESSARY_SYMBOL_STR,
305 "unnecessary conversion between Symbol and string"
308 declare_clippy_lint! {
309 /// Finds unidiomatic usage of `if_chain!`
312 "non-idiomatic `if_chain!` usage"
315 declare_clippy_lint! {
317 /// Checks for invalid `clippy::version` attributes.
319 /// Valid values are:
321 /// * any valid semantic version
322 pub INVALID_CLIPPY_VERSION_ATTRIBUTE,
324 "found an invalid `clippy::version` attribute"
327 declare_clippy_lint! {
329 /// Checks for declared clippy lints without the `clippy::version` attribute.
331 pub MISSING_CLIPPY_VERSION_ATTRIBUTE,
333 "found clippy lint without `clippy::version` attribute"
336 declare_clippy_lint! {
338 /// Check that the `extract_msrv_attr!` macro is used, when a lint has a MSRV.
340 pub MISSING_MSRV_ATTR_IMPL,
342 "checking if all necessary steps were taken when adding a MSRV to a lint"
345 declare_clippy_lint! {
347 /// Checks for cases of an auto-generated deprecated lint without an updated reason,
348 /// i.e. `"default deprecation note"`.
350 /// ### Why is this bad?
351 /// Indicates that the documentation is incomplete.
355 /// declare_deprecated_lint! {
356 /// /// ### What it does
357 /// /// Nothing. This lint has been deprecated.
359 /// /// ### Deprecation reason
361 /// #[clippy::version = "1.63.0"]
363 /// "default deprecation note"
369 /// declare_deprecated_lint! {
370 /// /// ### What it does
371 /// /// Nothing. This lint has been deprecated.
373 /// /// ### Deprecation reason
374 /// /// This lint has been replaced by `cooler_lint`
375 /// #[clippy::version = "1.63.0"]
377 /// "this lint has been replaced by `cooler_lint`"
380 pub DEFAULT_DEPRECATION_REASON,
382 "found 'default deprecation note' in a deprecated lint declaration"
385 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
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;
395 let name = item.ident.as_str();
396 if let Some(last_name) = last_name {
397 if *last_name > *name {
400 CLIPPY_LINTS_INTERNAL,
402 "this constant should be before the previous constant due to lexical \
407 last_name = Some(name);
416 #[derive(Clone, Debug, Default)]
417 pub struct LintWithoutLintPass {
418 declared_lints: FxHashMap<Symbol, Span>,
419 registered_lints: FxHashSet<Symbol>,
422 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS, INVALID_CLIPPY_VERSION_ATTRIBUTE, MISSING_CLIPPY_VERSION_ATTRIBUTE, DEFAULT_DEPRECATION_REASON]);
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())
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);
437 let expr = &cx.tcx.hir().body(body_id).value;
440 if let ExprKind::AddrOf(_, _, inner_exp) = expr.kind
441 && let ExprKind::Struct(_, struct_fields, _) = inner_exp.kind {
442 fields = struct_fields;
446 } else if let ExprKind::Struct(_, struct_fields, _) = expr.kind {
447 fields = struct_fields;
454 .find(|f| f.ident.as_str() == "desc")
455 .expect("lints must have a description field");
457 if let ExprKind::Lit(Spanned {
458 node: LitKind::Str(ref sym, _),
462 let sym_str = sym.as_str();
464 if sym_str == "default lint description" {
469 &format!("the lint `{}` has the default lint description", item.ident.name),
473 self.declared_lints.insert(item.ident.name, item.span);
474 } else if sym_str == "default deprecation note" {
477 DEFAULT_DEPRECATION_REASON,
479 &format!("the lint `{}` has the default deprecation reason", item.ident.name),
484 } else if let Some(macro_call) = root_macro_call_first_node(cx, item) {
486 cx.tcx.item_name(macro_call.def_id).as_str(),
487 "impl_lint_pass" | "declare_lint_pass"
491 if let hir::ItemKind::Impl(hir::Impl {
493 items: impl_item_refs,
497 let mut collector = LintCollector {
498 output: &mut self.registered_lints,
501 let body_id = cx.tcx.hir().body_owned_by(
502 cx.tcx.hir().local_def_id(
505 .find(|iiref| iiref.ident.as_str() == "get_lints")
506 .expect("LintPass needs to implement get_lints")
511 collector.visit_expr(cx.tcx.hir().body(body_id).value);
516 fn check_crate_post(&mut self, cx: &LateContext<'tcx>) {
517 if is_lint_allowed(cx, LINT_WITHOUT_LINT_PASS, CRATE_HIR_ID) {
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;
531 if !self.registered_lints.contains(lint_name) {
534 LINT_WITHOUT_LINT_PASS,
536 &format!("the lint `{lint_name}` is not added to any `LintPass`"),
543 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &hir::Ty<'_>) -> bool {
548 mutbl: Mutability::Not,
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);
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") {
570 if RustcVersion::parse(value.as_str()).is_err() {
573 INVALID_CLIPPY_VERSION_ATTRIBUTE,
575 "this item has an invalid `clippy::version` attribute",
577 "please use a valid semantic version, see `doc/adding_lints.md`",
583 MISSING_CLIPPY_VERSION_ATTRIBUTE,
585 "this lint is missing the `clippy::version` attribute or version value",
587 "please use a `clippy::version` attribute, see `doc/adding_lints.md`",
592 /// This function extracts the version value of a `clippy::version` attribute if the given value has
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| {
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();
613 struct LintCollector<'a, 'tcx> {
614 output: &'a mut FxHashSet<Symbol>,
615 cx: &'a LateContext<'tcx>,
618 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
619 type NestedFilter = nested_filter::All;
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);
627 fn nested_visit_map(&mut self) -> Self::Map {
632 #[derive(Clone, Default)]
633 pub struct CompilerLintFunctions {
634 map: FxHashMap<&'static str, &'static str>,
637 impl CompilerLintFunctions {
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");
650 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
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) {
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);
668 COMPILER_LINT_FUNCTIONS,
670 "usage of a compiler lint function",
672 &format!("please use the Clippy variant of this function: `{sugg}`"),
679 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
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) {
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();
690 if let ["expn_data", "outer_expn"] = method_names.as_slice();
691 let (self_arg, args)= arg_lists[1];
693 let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
694 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
698 OUTER_EXPN_EXPN_DATA,
699 spans[1].with_hi(expr.span.hi()),
700 "usage of `outer_expn().expn_data()`",
702 "outer_expn_data()".to_string(),
703 Applicability::MachineApplicable,
710 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
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?");
718 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
720 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
721 FnKind::Closure(..) => false,
725 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
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) {
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;
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));
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);
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);
758 let help_snippet = snippet(cx, span_call_args[0].span, r#""...""#);
759 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
762 let note_snippet = snippet(cx, span_call_args[0].span, r#""...""#);
763 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
772 struct AndThenSnippets<'a> {
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#""...""#);
793 struct SpanSuggestionSnippets<'a> {
796 applicability: Cow<'a, str>,
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");
807 SpanSuggestionSnippets {
810 applicability: applicability_snippet,
814 fn suggest_suggestion(
815 cx: &LateContext<'_>,
817 and_then_snippets: &AndThenSnippets<'_>,
818 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
822 COLLAPSIBLE_SPAN_LINT_CALLS,
824 "this call is collapsible",
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
836 Applicability::MachineApplicable,
841 cx: &LateContext<'_>,
843 and_then_snippets: &AndThenSnippets<'_>,
847 let option_span = if with_span {
848 format!("Some({})", and_then_snippets.span)
855 COLLAPSIBLE_SPAN_LINT_CALLS,
857 "this call is collapsible",
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,
863 Applicability::MachineApplicable,
868 cx: &LateContext<'_>,
870 and_then_snippets: &AndThenSnippets<'_>,
874 let note_span = if with_span {
875 format!("Some({})", and_then_snippets.span)
882 COLLAPSIBLE_SPAN_LINT_CALLS,
884 "this call is collapsible",
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,
890 Applicability::MachineApplicable,
894 declare_lint_pass!(UnnecessaryDefPath => [UNNECESSARY_DEF_PATH]);
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<'_>) {
901 DiagnosticItem(Symbol),
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"],
910 if is_lint_allowed(cx, UNNECESSARY_DEF_PATH, expr.hir_id) {
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();
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(
935 Ident::from_str(method_name),
941 .map_or(def_id, |item| item.def_id)
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)
951 "use of a def path to a diagnostic item",
952 Item::DiagnosticItem(*item_name),
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;
958 "use of a def path to a `LangItem`",
959 Item::LangItem(item_name),
965 let has_ctor = match cx.tcx.def_kind(def_id) {
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())
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())
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) {
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})"),
988 // match_trait_method
989 (1, Item::DiagnosticItem(item)) =>
990 (format!("is_trait_method({cx_snip}, {def_snip}, sym::{item})"), false),
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 => (
999 "is_res_diag_ctor({cx_snip}, path_res({cx_snip}, {def_snip}), sym::{item})",
1003 (3, Item::LangItem(item)) if has_ctor => (
1005 "is_res_lang_ctor({cx_snip}, path_res({cx_snip}, {def_snip}), LangItem::{item})",
1009 (3, Item::DiagnosticItem(item)) =>
1010 (format!("is_path_diagnostic_item({cx_snip}, {def_snip}, sym::{item})"), false),
1011 (3, Item::LangItem(item)) => (
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))",
1023 UNNECESSARY_DEF_PATH,
1027 diag.span_suggestion(expr.span, "try", sugg, app);
1030 "if this `DefId` came from a constructor expression or pattern then the \
1031 parent `DefId` should be used instead"
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)
1052 Res::Def(DefKind::Static(_), def_id) => read_mir_alloc_def_path(
1054 cx.tcx.eval_static_initializer(def_id).ok()?.inner(),
1055 cx.tcx.type_of(def_id),
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))
1065 ExprKind::Array(exprs) => exprs
1068 if let ExprKind::Lit(lit) = &expr.kind {
1069 if let LitKind::Str(sym, _) = lit.node {
1070 return Some((*sym.as_str()).to_owned());
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) {
1093 if let ty::Array(ty, _) | ty::Slice(ty) = *ty.kind()
1094 && let ty::Ref(_, ty, Mutability::Not) = *ty.kind()
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)
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 {
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,
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()..] {
1140 cx.tcx.def_kind(*item_def_id),
1141 DefKind::Mod | DefKind::Enum | DefKind::Trait
1143 for child in cx.tcx.module_children(*item_def_id) {
1144 if child.ident.name == *item {
1149 for child in cx.tcx.associated_item_def_ids(*item_def_id) {
1150 if cx.tcx.item_name(*child) == *item {
1162 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
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());
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();
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 {
1182 // We checked the type of the constant above
1186 if !check_path(cx, &path[..]);
1188 span_lint(cx, INVALID_PATHS, item.span, "invalid path");
1195 pub struct InterningDefinedSymbol {
1196 // Maps the symbol value to the constant DefId.
1197 symbol_map: FxHashMap<u32, DefId>,
1200 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
1202 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
1203 fn check_crate(&mut self, cx: &LateContext<'_>) {
1204 if !self.symbol_map.is_empty() {
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() {
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();
1218 self.symbol_map.insert(value, item_def_id);
1226 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
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);
1237 INTERNING_DEFINED_SYMBOL,
1238 is_expn_of(expr.span, "sym").unwrap_or(expr.span),
1239 "interning a defined symbol",
1241 cx.tcx.def_path_str(def_id),
1242 Applicability::MachineApplicable,
1246 if let ExprKind::Binary(op, left, right) = expr.kind {
1247 if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
1249 (left, self.symbol_str_expr(left, cx)),
1250 (right, self.symbol_str_expr(right, cx)),
1253 // both operands are a symbol string
1254 [(_, Some(left)), (_, Some(right))] => {
1257 UNNECESSARY_SYMBOL_STR,
1259 "unnecessary `Symbol` to string conversion",
1263 left.as_symbol_snippet(cx),
1265 right.as_symbol_snippet(cx),
1267 Applicability::MachineApplicable,
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, .. }) {
1276 UNNECESSARY_SYMBOL_STR,
1278 "unnecessary string allocation",
1280 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
1281 Applicability::MachineApplicable,
1286 [(_, None), (_, None)] => {},
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,
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 }
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) {
1314 } else if match_type(cx, ty, &paths::IDENT) {
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));
1323 let is_to_owned = path.last().unwrap().ends_with("string");
1324 return Some(SymbolStrExpr::Expr {
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));
1343 enum SymbolStrExpr<'tcx> {
1344 /// a string constant with a corresponding symbol constant
1346 /// a "symbol to string" expression like `symbol.as_str()`
1348 /// part that evaluates to `Symbol` or `Ident`
1349 item: &'tcx Expr<'tcx>,
1351 /// whether an owned `String` is created like `to_ident_string()`
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> {
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(), "..");
1365 snip.to_mut().push_str(".name");
1373 declare_lint_pass!(IfChainStyle => [IF_CHAIN_STYLE]);
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 }
1382 if is_first_if_chain_expr(cx, block.hir_id, if_chain_span) {
1386 if_chain_local_span(cx, local, if_chain_span),
1387 "`let` expression should be above the `if_chain!`",
1389 } else if local.span.ctxt() == block.span.ctxt() && is_if_chain_then(after, block.expr, if_chain_span) {
1393 if_chain_local_span(cx, local, if_chain_span),
1394 "`let` expression should be inside `then { .. }`",
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())
1405 let ExprKind::Block(then_block, _) = then.kind else { return };
1406 let if_chain_span = is_expn_of(expr.span, "if_chain");
1408 check_nested_if_chains(cx, expr, then_block, if_chain_span);
1410 let Some(if_chain_span) = if_chain_span else { return };
1411 // check for `if a && b;`
1413 if let ExprKind::Binary(op, _, _) = cond.kind;
1414 if op.node == BinOpKind::And;
1415 if cx.sess().source_map().is_multiline(cond.span);
1417 span_lint(cx, IF_CHAIN_STYLE, cond.span, "`if a && b;` should be `if a; if b;`");
1420 if is_first_if_chain_expr(cx, expr.hir_id, if_chain_span)
1421 && is_if_chain_then(then_block.stmts, then_block.expr, if_chain_span)
1423 span_lint(cx, IF_CHAIN_STYLE, expr.span, "`if_chain!` only has one `if`");
1428 fn check_nested_if_chains(
1429 cx: &LateContext<'_>,
1431 then_block: &Block<'_>,
1432 if_chain_span: Option<Span>,
1435 let (head, tail) = match *then_block {
1436 Block { stmts, expr: Some(tail), .. } => (stmts, tail),
1440 Stmt { kind: StmtKind::Expr(tail) | StmtKind::Semi(tail), .. }
1447 if let Some(higher::IfOrIfLet { r#else: None, .. }) = higher::IfOrIfLet::hir(tail);
1448 let sm = cx.sess().source_map();
1451 .all(|stmt| matches!(stmt.kind, StmtKind::Local(..)) && !sm.is_multiline(stmt.span));
1452 if if_chain_span.is_some() || !is_else_clause(cx.tcx, if_expr);
1453 then {} else { return }
1455 let (span, msg) = match (if_chain_span, is_expn_of(tail.span, "if_chain")) {
1456 (None, Some(_)) => (if_expr.span, "this `if` can be part of the inner `if_chain!`"),
1457 (Some(_), None) => (tail.span, "this `if` can be part of the outer `if_chain!`"),
1458 (Some(a), Some(b)) if a != b => (b, "this `if_chain!` can be merged with the outer `if_chain!`"),
1461 span_lint_and_then(cx, IF_CHAIN_STYLE, span, msg, |diag| {
1462 let (span, msg) = match head {
1464 [stmt] => (stmt.span, "this `let` statement can also be in the `if_chain!`"),
1467 "these `let` statements can also be in the `if_chain!`",
1470 diag.span_help(span, msg);
1474 fn is_first_if_chain_expr(cx: &LateContext<'_>, hir_id: HirId, if_chain_span: Span) -> bool {
1477 .parent_iter(hir_id)
1480 !matches!(node, Node::Expr(Expr { kind: ExprKind::Block(..), .. }) | Node::Stmt(_))
1482 .map_or(false, |(id, _)| {
1483 is_expn_of(cx.tcx.hir().span(id), "if_chain") != Some(if_chain_span)
1487 /// Checks a trailing slice of statements and expression of a `Block` to see if they are part
1488 /// of the `then {..}` portion of an `if_chain!`
1489 fn is_if_chain_then(stmts: &[Stmt<'_>], expr: Option<&Expr<'_>>, if_chain_span: Span) -> bool {
1490 let span = if let [stmt, ..] = stmts {
1492 } else if let Some(expr) = expr {
1498 is_expn_of(span, "if_chain").map_or(true, |span| span != if_chain_span)
1501 /// Creates a `Span` for `let x = ..;` in an `if_chain!` call.
1502 fn if_chain_local_span(cx: &LateContext<'_>, local: &Local<'_>, if_chain_span: Span) -> Span {
1503 let mut span = local.pat.span;
1504 if let Some(init) = local.init {
1505 span = span.to(init.span);
1507 span.adjust(if_chain_span.ctxt().outer_expn());
1508 let sm = cx.sess().source_map();
1509 let span = sm.span_extend_to_prev_str(span, "let", false, true).unwrap_or(span);
1510 let span = sm.span_extend_to_next_char(span, ';', false);
1512 span.lo() - BytePos(3),
1513 span.hi() + BytePos(1),
1519 declare_lint_pass!(MsrvAttrImpl => [MISSING_MSRV_ATTR_IMPL]);
1521 impl LateLintPass<'_> for MsrvAttrImpl {
1522 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1524 if let hir::ItemKind::Impl(hir::Impl {
1525 of_trait: Some(lint_pass_trait_ref),
1530 if let Some(lint_pass_trait_def_id) = lint_pass_trait_ref.trait_def_id();
1531 let is_late_pass = match_def_path(cx, lint_pass_trait_def_id, &paths::LATE_LINT_PASS);
1532 if is_late_pass || match_def_path(cx, lint_pass_trait_def_id, &paths::EARLY_LINT_PASS);
1533 let self_ty = hir_ty_to_ty(cx.tcx, self_ty);
1534 if let ty::Adt(self_ty_def, _) = self_ty.kind();
1535 if self_ty_def.is_struct();
1536 if self_ty_def.all_fields().any(|f| {
1540 .filter(|t| matches!(t.unpack(), GenericArgKind::Type(_)))
1541 .any(|t| match_type(cx, t.expect_ty(), &paths::RUSTC_VERSION))
1543 if !items.iter().any(|item| item.ident.name == sym!(enter_lint_attrs));
1545 let context = if is_late_pass { "LateContext" } else { "EarlyContext" };
1546 let lint_pass = if is_late_pass { "LateLintPass" } else { "EarlyLintPass" };
1547 let span = cx.sess().source_map().span_through_char(item.span, '{');
1550 MISSING_MSRV_ATTR_IMPL,
1552 &format!("`extract_msrv_attr!` macro missing from `{lint_pass}` implementation"),
1553 &format!("add `extract_msrv_attr!({context})` to the `{lint_pass}` implementation"),
1554 format!("{}\n extract_msrv_attr!({context});", snippet(cx, span, "..")),
1555 Applicability::MachineApplicable,