1 use clippy_utils::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::match_type;
6 higher, is_else_clause, is_expn_of, is_expr_path_def_path, is_lint_allowed, match_def_path, method_calls,
7 path_to_res, paths, peel_blocks_with_stmt, SpanlessEq,
9 use if_chain::if_chain;
11 use rustc_ast::ast::{Crate, ItemKind, LitKind, ModKind, NodeId};
12 use rustc_ast::visit::FnKind;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_errors::Applicability;
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::def_id::DefId;
18 use rustc_hir::hir_id::CRATE_HIR_ID;
19 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
21 BinOpKind, Block, Expr, ExprKind, HirId, Item, Local, MutTy, Mutability, Node, Path, Stmt, StmtKind, Ty, TyKind,
24 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
25 use rustc_middle::hir::map::Map;
26 use rustc_middle::mir::interpret::ConstValue;
28 use rustc_semver::RustcVersion;
29 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
30 use rustc_span::source_map::Spanned;
31 use rustc_span::symbol::{Symbol, SymbolStr};
32 use rustc_span::{sym, BytePos, Span};
33 use rustc_typeck::hir_ty_to_ty;
35 use std::borrow::{Borrow, Cow};
37 #[cfg(feature = "metadata-collector-lint")]
38 pub mod metadata_collector;
40 declare_clippy_lint! {
42 /// Checks for various things we like to keep tidy in clippy.
44 /// ### Why is this bad?
45 /// We like to pretend we're an example of tidy code.
48 /// Wrong ordering of the util::paths constants.
49 pub CLIPPY_LINTS_INTERNAL,
51 "various things that will negatively affect your clippy experience"
54 declare_clippy_lint! {
56 /// Ensures every lint is associated to a `LintPass`.
58 /// ### Why is this bad?
59 /// The compiler only knows lints via a `LintPass`. Without
60 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
61 /// know the name of the lint.
63 /// ### Known problems
64 /// Only checks for lints associated using the
65 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
69 /// declare_lint! { pub LINT_1, ... }
70 /// declare_lint! { pub LINT_2, ... }
71 /// declare_lint! { pub FORGOTTEN_LINT, ... }
73 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
74 /// // missing FORGOTTEN_LINT
76 pub LINT_WITHOUT_LINT_PASS,
78 "declaring a lint without associating it in a LintPass"
81 declare_clippy_lint! {
83 /// Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
84 /// variant of the function.
86 /// ### Why is this bad?
87 /// The `utils::*` variants also add a link to the Clippy documentation to the
88 /// warning/error messages.
93 /// cx.span_lint(LINT_NAME, "message");
98 /// utils::span_lint(cx, LINT_NAME, "message");
100 pub COMPILER_LINT_FUNCTIONS,
102 "usage of the lint functions of the compiler instead of the utils::* variant"
105 declare_clippy_lint! {
107 /// Checks for calls to `cx.outer().expn_data()` and suggests to use
108 /// the `cx.outer_expn_data()`
110 /// ### Why is this bad?
111 /// `cx.outer_expn_data()` is faster and more concise.
116 /// expr.span.ctxt().outer().expn_data()
121 /// expr.span.ctxt().outer_expn_data()
123 pub OUTER_EXPN_EXPN_DATA,
125 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
128 declare_clippy_lint! {
130 /// Not an actual lint. This lint is only meant for testing our customized internal compiler
131 /// error message by calling `panic`.
133 /// ### Why is this bad?
134 /// ICE in large quantities can damage your teeth
143 "this message should not appear anywhere as we ICE before and don't emit the lint"
146 declare_clippy_lint! {
148 /// Checks for cases of an auto-generated lint without an updated description,
149 /// i.e. `default lint description`.
151 /// ### Why is this bad?
152 /// Indicates that the lint is not finished.
157 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
162 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
166 "found 'default lint description' in a lint declaration"
169 declare_clippy_lint! {
171 /// Lints `span_lint_and_then` function calls, where the
172 /// closure argument has only one statement and that statement is a method
173 /// call to `span_suggestion`, `span_help`, `span_note` (using the same
174 /// span), `help` or `note`.
176 /// These usages of `span_lint_and_then` should be replaced with one of the
177 /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
178 /// `span_lint_and_note`.
180 /// ### Why is this bad?
181 /// Using the wrapper `span_lint_and_*` functions, is more
182 /// 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 calls to `utils::match_type()` on a type diagnostic item
233 /// and suggests to use `utils::is_type_diagnostic_item()` instead.
235 /// ### Why is this bad?
236 /// `utils::is_type_diagnostic_item()` does not require hardcoded paths.
241 /// utils::match_type(cx, ty, &paths::VEC)
246 /// utils::is_type_diagnostic_item(cx, ty, sym::Vec)
248 pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
250 "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
253 declare_clippy_lint! {
255 /// Checks the paths module for invalid paths.
257 /// ### Why is this bad?
258 /// It indicates a bug in the code.
267 declare_clippy_lint! {
269 /// Checks for interning symbols that have already been pre-interned and defined as constants.
271 /// ### Why is this bad?
272 /// It's faster and easier to use the symbol constant.
277 /// let _ = sym!(f32);
282 /// let _ = sym::f32;
284 pub INTERNING_DEFINED_SYMBOL,
286 "interning a symbol that is pre-interned and defined as a constant"
289 declare_clippy_lint! {
291 /// Checks for unnecessary conversion from Symbol to a string.
293 /// ### Why is this bad?
294 /// It's faster use symbols directly intead of strings.
299 /// symbol.as_str() == "clippy";
304 /// symbol == sym::clippy;
306 pub UNNECESSARY_SYMBOL_STR,
308 "unnecessary conversion between Symbol and string"
311 declare_clippy_lint! {
312 /// Finds unidiomatic usage of `if_chain!`
315 "non-idiomatic `if_chain!` usage"
318 declare_clippy_lint! {
320 /// Checks for invalid `clippy::version` attributes.
322 /// Valid values are:
324 /// * any valid semantic version
325 pub INVALID_CLIPPY_VERSION_ATTRIBUTE,
327 "found an invalid `clippy::version` attribute"
330 declare_clippy_lint! {
332 /// Checks for declared clippy lints without the `clippy::version` attribute.
334 pub MISSING_CLIPPY_VERSION_ATTRIBUTE,
336 "found clippy lint without `clippy::version` attribute"
339 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
341 impl EarlyLintPass for ClippyLintsInternal {
342 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &Crate) {
343 if let Some(utils) = krate.items.iter().find(|item| item.ident.name.as_str() == "utils") {
344 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
345 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
346 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
347 let mut last_name: Option<SymbolStr> = None;
349 let name = item.ident.as_str();
350 if let Some(ref last_name) = last_name {
351 if **last_name > *name {
354 CLIPPY_LINTS_INTERNAL,
356 "this constant should be before the previous constant due to lexical \
361 last_name = Some(name);
370 #[derive(Clone, Debug, Default)]
371 pub struct LintWithoutLintPass {
372 declared_lints: FxHashMap<Symbol, Span>,
373 registered_lints: FxHashSet<Symbol>,
376 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS, INVALID_CLIPPY_VERSION_ATTRIBUTE, MISSING_CLIPPY_VERSION_ATTRIBUTE]);
378 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
379 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
380 if is_lint_allowed(cx, DEFAULT_LINT, item.hir_id()) {
384 if let hir::ItemKind::Static(ty, Mutability::Not, body_id) = item.kind {
385 if is_lint_ref_type(cx, ty) {
386 check_invalid_clippy_version_attribute(cx, item);
388 let expr = &cx.tcx.hir().body(body_id).value;
390 if let ExprKind::AddrOf(_, _, inner_exp) = expr.kind;
391 if let ExprKind::Struct(_, fields, _) = inner_exp.kind;
394 .find(|f| f.ident.as_str() == "desc")
395 .expect("lints must have a description field");
396 if let ExprKind::Lit(Spanned {
397 node: LitKind::Str(ref sym, _),
399 }) = field.expr.kind;
400 if sym.as_str() == "default lint description";
407 &format!("the lint `{}` has the default lint description", item.ident.name),
411 self.declared_lints.insert(item.ident.name, item.span);
413 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
414 || is_expn_of(item.span, "declare_lint_pass").is_some()
416 if let hir::ItemKind::Impl(hir::Impl {
418 items: impl_item_refs,
422 let mut collector = LintCollector {
423 output: &mut self.registered_lints,
426 let body_id = cx.tcx.hir().body_owned_by(
429 .find(|iiref| iiref.ident.as_str() == "get_lints")
430 .expect("LintPass needs to implement get_lints")
434 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
439 fn check_crate_post(&mut self, cx: &LateContext<'tcx>) {
440 if is_lint_allowed(cx, LINT_WITHOUT_LINT_PASS, CRATE_HIR_ID) {
444 for (lint_name, &lint_span) in &self.declared_lints {
445 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
446 // file points to "<rustc macros>".
447 // `compiletest-rs` thinks that's an error in a different file and
448 // just ignores it. This causes the test in compile-fail/lint_pass
449 // not able to capture the error.
450 // Therefore, we need to climb the macro expansion tree and find the
451 // actual span that invoked `declare_tool_lint!`:
452 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
454 if !self.registered_lints.contains(lint_name) {
457 LINT_WITHOUT_LINT_PASS,
459 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
466 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
471 mutbl: Mutability::Not,
475 if let TyKind::Path(ref path) = inner.kind {
476 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
477 return match_def_path(cx, def_id, &paths::LINT);
485 fn check_invalid_clippy_version_attribute(cx: &LateContext<'_>, item: &'_ Item<'_>) {
486 if let Some(value) = extract_clippy_version_value(cx, item) {
487 // The `sym!` macro doesn't work as it only expects a single token.
488 // It's better to keep it this way and have a direct `Symbol::intern` call here.
489 if value == Symbol::intern("pre 1.29.0") {
493 if RustcVersion::parse(&*value.as_str()).is_err() {
496 INVALID_CLIPPY_VERSION_ATTRIBUTE,
498 "this item has an invalid `clippy::version` attribute",
500 "please use a valid sematic version, see `doc/adding_lints.md`",
506 MISSING_CLIPPY_VERSION_ATTRIBUTE,
508 "this lint is missing the `clippy::version` attribute or version value",
510 "please use a `clippy::version` attribute, see `doc/adding_lints.md`",
515 /// This function extracts the version value of a `clippy::version` attribute if the given value has
517 fn extract_clippy_version_value(cx: &LateContext<'_>, item: &'_ Item<'_>) -> Option<Symbol> {
518 let attrs = cx.tcx.hir().attrs(item.hir_id());
519 attrs.iter().find_map(|attr| {
521 // Identify attribute
522 if let ast::AttrKind::Normal(ref attr_kind, _) = &attr.kind;
523 if let [tool_name, attr_name] = &attr_kind.path.segments[..];
524 if tool_name.ident.name == sym::clippy;
525 if attr_name.ident.name == sym::version;
526 if let Some(version) = attr.value_str();
536 struct LintCollector<'a, 'tcx> {
537 output: &'a mut FxHashSet<Symbol>,
538 cx: &'a LateContext<'tcx>,
541 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
542 type Map = Map<'tcx>;
544 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
545 if path.segments.len() == 1 {
546 self.output.insert(path.segments[0].ident.name);
550 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
551 NestedVisitorMap::All(self.cx.tcx.hir())
555 #[derive(Clone, Default)]
556 pub struct CompilerLintFunctions {
557 map: FxHashMap<&'static str, &'static str>,
560 impl CompilerLintFunctions {
562 pub fn new() -> Self {
563 let mut map = FxHashMap::default();
564 map.insert("span_lint", "utils::span_lint");
565 map.insert("struct_span_lint", "utils::span_lint");
566 map.insert("lint", "utils::span_lint");
567 map.insert("span_lint_note", "utils::span_lint_and_note");
568 map.insert("span_lint_help", "utils::span_lint_and_help");
573 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
575 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
576 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
577 if is_lint_allowed(cx, COMPILER_LINT_FUNCTIONS, expr.hir_id) {
582 if let ExprKind::MethodCall(path, _, [self_arg, ..], _) = &expr.kind;
583 let fn_name = path.ident;
584 if let Some(sugg) = self.map.get(&*fn_name.as_str());
585 let ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
586 if match_type(cx, ty, &paths::EARLY_CONTEXT)
587 || match_type(cx, ty, &paths::LATE_CONTEXT);
591 COMPILER_LINT_FUNCTIONS,
593 "usage of a compiler lint function",
595 &format!("please use the Clippy variant of this function: `{}`", sugg),
602 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
604 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
605 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
606 if is_lint_allowed(cx, OUTER_EXPN_EXPN_DATA, expr.hir_id) {
610 let (method_names, arg_lists, spans) = method_calls(expr, 2);
611 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
612 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
614 if let ["expn_data", "outer_expn"] = method_names.as_slice();
615 let args = arg_lists[1];
617 let self_arg = &args[0];
618 let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
619 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
623 OUTER_EXPN_EXPN_DATA,
624 spans[1].with_hi(expr.span.hi()),
625 "usage of `outer_expn().expn_data()`",
627 "outer_expn_data()".to_string(),
628 Applicability::MachineApplicable,
635 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
637 impl EarlyLintPass for ProduceIce {
638 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
639 assert!(!is_trigger_fn(fn_kind), "Would you like some help with that?");
643 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
645 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
646 FnKind::Closure(..) => false,
650 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
652 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
653 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
654 if is_lint_allowed(cx, COLLAPSIBLE_SPAN_LINT_CALLS, expr.hir_id) {
659 if let ExprKind::Call(func, and_then_args) = expr.kind;
660 if is_expr_path_def_path(cx, func, &["clippy_utils", "diagnostics", "span_lint_and_then"]);
661 if and_then_args.len() == 5;
662 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
663 let body = cx.tcx.hir().body(*body_id);
664 let only_expr = peel_blocks_with_stmt(&body.value);
665 if let ExprKind::MethodCall(ps, _, span_call_args, _) = &only_expr.kind;
667 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
668 let mut sle = SpanlessEq::new(cx).deny_side_effects();
669 match &*ps.ident.as_str() {
670 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
671 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
673 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
674 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
675 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
677 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
678 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
679 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
682 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
683 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
686 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
687 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
696 struct AndThenSnippets<'a> {
703 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
704 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
705 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
706 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
707 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
717 struct SpanSuggestionSnippets<'a> {
720 applicability: Cow<'a, str>,
723 fn span_suggestion_snippets<'a, 'hir>(
724 cx: &LateContext<'_>,
725 span_call_args: &'hir [Expr<'hir>],
726 ) -> SpanSuggestionSnippets<'a> {
727 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
728 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
729 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
731 SpanSuggestionSnippets {
734 applicability: applicability_snippet,
738 fn suggest_suggestion(
739 cx: &LateContext<'_>,
741 and_then_snippets: &AndThenSnippets<'_>,
742 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
746 COLLAPSIBLE_SPAN_LINT_CALLS,
748 "this call is collapsible",
751 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
752 and_then_snippets.cx,
753 and_then_snippets.lint,
754 and_then_snippets.span,
755 and_then_snippets.msg,
756 span_suggestion_snippets.help,
757 span_suggestion_snippets.sugg,
758 span_suggestion_snippets.applicability
760 Applicability::MachineApplicable,
765 cx: &LateContext<'_>,
767 and_then_snippets: &AndThenSnippets<'_>,
771 let option_span = if with_span {
772 format!("Some({})", and_then_snippets.span)
779 COLLAPSIBLE_SPAN_LINT_CALLS,
781 "this call is collapsible",
784 "span_lint_and_help({}, {}, {}, {}, {}, {})",
785 and_then_snippets.cx,
786 and_then_snippets.lint,
787 and_then_snippets.span,
788 and_then_snippets.msg,
792 Applicability::MachineApplicable,
797 cx: &LateContext<'_>,
799 and_then_snippets: &AndThenSnippets<'_>,
803 let note_span = if with_span {
804 format!("Some({})", and_then_snippets.span)
811 COLLAPSIBLE_SPAN_LINT_CALLS,
813 "this call is collspible",
816 "span_lint_and_note({}, {}, {}, {}, {}, {})",
817 and_then_snippets.cx,
818 and_then_snippets.lint,
819 and_then_snippets.span,
820 and_then_snippets.msg,
824 Applicability::MachineApplicable,
828 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
830 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
831 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
832 if is_lint_allowed(cx, MATCH_TYPE_ON_DIAGNOSTIC_ITEM, expr.hir_id) {
837 // Check if this is a call to utils::match_type()
838 if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
839 if is_expr_path_def_path(cx, fn_path, &["clippy_utils", "ty", "match_type"]);
840 // Extract the path to the matched type
841 if let Some(segments) = path_to_matched_type(cx, ty_path);
842 let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
843 if let Some(ty_did) = path_to_res(cx, &segments[..]).opt_def_id();
844 // Check if the matched type is a diagnostic item
845 if let Some(item_name) = cx.tcx.get_diagnostic_name(ty_did);
847 // TODO: check paths constants from external crates.
848 let cx_snippet = snippet(cx, context.span, "_");
849 let ty_snippet = snippet(cx, ty.span, "_");
853 MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
855 "usage of `clippy_utils::ty::match_type()` on a type diagnostic item",
857 format!("clippy_utils::ty::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
858 Applicability::MaybeIncorrect,
865 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
866 use rustc_hir::ItemKind;
869 ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
870 ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
871 Res::Local(hir_id) => {
872 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
873 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
874 if let Some(init) = local.init {
875 return path_to_matched_type(cx, init);
879 Res::Def(DefKind::Const | DefKind::Static, def_id) => {
880 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
881 if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
882 let body = cx.tcx.hir().body(body_id);
883 return path_to_matched_type(cx, &body.value);
889 ExprKind::Array(exprs) => {
890 let segments: Vec<SymbolStr> = exprs
893 if let ExprKind::Lit(lit) = &expr.kind {
894 if let LitKind::Str(sym, _) = lit.node {
895 return Some(sym.as_str());
903 if segments.len() == exprs.len() {
904 return Some(segments);
913 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
914 // module. That's all it does and all it needs to do.
915 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
916 if path_to_res(cx, path) != Res::Err {
920 // Some implementations can't be found by `path_to_res`, particularly inherent
921 // implementations of native types. Check lang items.
922 let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
923 let lang_items = cx.tcx.lang_items();
924 for item_def_id in lang_items.items().iter().flatten() {
925 let lang_item_path = cx.get_def_path(*item_def_id);
926 if path_syms.starts_with(&lang_item_path) {
927 if let [item] = &path_syms[lang_item_path.len()..] {
928 for child in cx.tcx.item_children(*item_def_id) {
929 if child.ident.name == *item {
940 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
942 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
943 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
944 let local_def_id = &cx.tcx.parent_module(item.hir_id());
945 let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
947 if mod_name.as_str() == "paths";
948 if let hir::ItemKind::Const(ty, body_id) = item.kind;
949 let ty = hir_ty_to_ty(cx.tcx, ty);
950 if let ty::Array(el_ty, _) = &ty.kind();
951 if let ty::Ref(_, el_ty, _) = &el_ty.kind();
953 let body = cx.tcx.hir().body(body_id);
954 let typeck_results = cx.tcx.typeck_body(body_id);
955 if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
956 let path: Vec<&str> = path.iter().map(|x| {
957 if let Constant::Str(s) = x {
960 // We checked the type of the constant above
964 if !check_path(cx, &path[..]);
966 span_lint(cx, INVALID_PATHS, item.span, "invalid path");
973 pub struct InterningDefinedSymbol {
974 // Maps the symbol value to the constant DefId.
975 symbol_map: FxHashMap<u32, DefId>,
978 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
980 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
981 fn check_crate(&mut self, cx: &LateContext<'_>) {
982 if !self.symbol_map.is_empty() {
986 for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
987 if let Some(def_id) = path_to_res(cx, module).opt_def_id() {
988 for item in cx.tcx.item_children(def_id).iter() {
990 if let Res::Def(DefKind::Const, item_def_id) = item.res;
991 let ty = cx.tcx.type_of(item_def_id);
992 if match_type(cx, ty, &paths::SYMBOL);
993 if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
994 if let Ok(value) = value.to_u32();
996 self.symbol_map.insert(value, item_def_id);
1004 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
1006 if let ExprKind::Call(func, [arg]) = &expr.kind;
1007 if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
1008 if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
1009 if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
1010 let value = Symbol::intern(&arg).as_u32();
1011 if let Some(&def_id) = self.symbol_map.get(&value);
1015 INTERNING_DEFINED_SYMBOL,
1016 is_expn_of(expr.span, "sym").unwrap_or(expr.span),
1017 "interning a defined symbol",
1019 cx.tcx.def_path_str(def_id),
1020 Applicability::MachineApplicable,
1024 if let ExprKind::Binary(op, left, right) = expr.kind {
1025 if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
1027 (left, self.symbol_str_expr(left, cx)),
1028 (right, self.symbol_str_expr(right, cx)),
1031 // both operands are a symbol string
1032 [(_, Some(left)), (_, Some(right))] => {
1035 UNNECESSARY_SYMBOL_STR,
1037 "unnecessary `Symbol` to string conversion",
1041 left.as_symbol_snippet(cx),
1043 right.as_symbol_snippet(cx),
1045 Applicability::MachineApplicable,
1048 // one of the operands is a symbol string
1049 [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
1050 // creating an owned string for comparison
1051 if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
1054 UNNECESSARY_SYMBOL_STR,
1056 "unnecessary string allocation",
1058 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
1059 Applicability::MachineApplicable,
1064 [(_, None), (_, None)] => {},
1071 impl InterningDefinedSymbol {
1072 fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
1073 static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
1074 static SYMBOL_STR_PATHS: &[&[&str]] = &[
1075 &paths::SYMBOL_AS_STR,
1076 &paths::SYMBOL_TO_IDENT_STRING,
1077 &paths::TO_STRING_METHOD,
1079 // SymbolStr might be de-referenced: `&*symbol.as_str()`
1080 let call = if_chain! {
1081 if let ExprKind::AddrOf(_, _, e) = expr.kind;
1082 if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
1083 then { e } else { expr }
1087 if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1088 if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1089 let ty = cx.typeck_results().expr_ty(item);
1090 // ...on either an Ident or a Symbol
1091 if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1093 } else if match_type(cx, ty, &paths::IDENT) {
1098 // ...which converts it to a string
1099 let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1100 if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1102 let is_to_owned = path.last().unwrap().ends_with("string");
1103 return Some(SymbolStrExpr::Expr {
1110 // is a string constant
1111 if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1112 let value = Symbol::intern(&s).as_u32();
1113 // ...which matches a symbol constant
1114 if let Some(&def_id) = self.symbol_map.get(&value) {
1115 return Some(SymbolStrExpr::Const(def_id));
1122 enum SymbolStrExpr<'tcx> {
1123 /// a string constant with a corresponding symbol constant
1125 /// a "symbol to string" expression like `symbol.as_str()`
1127 /// part that evaluates to `Symbol` or `Ident`
1128 item: &'tcx Expr<'tcx>,
1130 /// whether an owned `String` is created like `to_ident_string()`
1135 impl<'tcx> SymbolStrExpr<'tcx> {
1136 /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1137 fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1139 Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1140 Self::Expr { item, is_ident, .. } => {
1141 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1144 snip.to_mut().push_str(".name");
1152 declare_lint_pass!(IfChainStyle => [IF_CHAIN_STYLE]);
1154 impl<'tcx> LateLintPass<'tcx> for IfChainStyle {
1155 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
1156 let (local, after, if_chain_span) = if_chain! {
1157 if let [Stmt { kind: StmtKind::Local(local), .. }, after @ ..] = block.stmts;
1158 if let Some(if_chain_span) = is_expn_of(block.span, "if_chain");
1159 then { (local, after, if_chain_span) } else { return }
1161 if is_first_if_chain_expr(cx, block.hir_id, if_chain_span) {
1165 if_chain_local_span(cx, local, if_chain_span),
1166 "`let` expression should be above the `if_chain!`",
1168 } else if local.span.ctxt() == block.span.ctxt() && is_if_chain_then(after, block.expr, if_chain_span) {
1172 if_chain_local_span(cx, local, if_chain_span),
1173 "`let` expression should be inside `then { .. }`",
1178 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1179 let (cond, then, els) = if let Some(higher::IfOrIfLet { cond, r#else, then }) = higher::IfOrIfLet::hir(expr) {
1180 (cond, then, r#else.is_some())
1184 let then_block = match then.kind {
1185 ExprKind::Block(block, _) => block,
1188 let if_chain_span = is_expn_of(expr.span, "if_chain");
1190 check_nested_if_chains(cx, expr, then_block, if_chain_span);
1192 let if_chain_span = match if_chain_span {
1196 // check for `if a && b;`
1198 if let ExprKind::Binary(op, _, _) = cond.kind;
1199 if op.node == BinOpKind::And;
1200 if cx.sess().source_map().is_multiline(cond.span);
1202 span_lint(cx, IF_CHAIN_STYLE, cond.span, "`if a && b;` should be `if a; if b;`");
1205 if is_first_if_chain_expr(cx, expr.hir_id, if_chain_span)
1206 && is_if_chain_then(then_block.stmts, then_block.expr, if_chain_span)
1208 span_lint(cx, IF_CHAIN_STYLE, expr.span, "`if_chain!` only has one `if`");
1213 fn check_nested_if_chains(
1214 cx: &LateContext<'_>,
1216 then_block: &Block<'_>,
1217 if_chain_span: Option<Span>,
1220 let (head, tail) = match *then_block {
1221 Block { stmts, expr: Some(tail), .. } => (stmts, tail),
1225 Stmt { kind: StmtKind::Expr(tail) | StmtKind::Semi(tail), .. }
1232 if let Some(higher::IfOrIfLet { r#else: None, .. }) = higher::IfOrIfLet::hir(tail);
1233 let sm = cx.sess().source_map();
1236 .all(|stmt| matches!(stmt.kind, StmtKind::Local(..)) && !sm.is_multiline(stmt.span));
1237 if if_chain_span.is_some() || !is_else_clause(cx.tcx, if_expr);
1238 then {} else { return }
1240 let (span, msg) = match (if_chain_span, is_expn_of(tail.span, "if_chain")) {
1241 (None, Some(_)) => (if_expr.span, "this `if` can be part of the inner `if_chain!`"),
1242 (Some(_), None) => (tail.span, "this `if` can be part of the outer `if_chain!`"),
1243 (Some(a), Some(b)) if a != b => (b, "this `if_chain!` can be merged with the outer `if_chain!`"),
1246 span_lint_and_then(cx, IF_CHAIN_STYLE, span, msg, |diag| {
1247 let (span, msg) = match head {
1249 [stmt] => (stmt.span, "this `let` statement can also be in the `if_chain!`"),
1252 "these `let` statements can also be in the `if_chain!`",
1255 diag.span_help(span, msg);
1259 fn is_first_if_chain_expr(cx: &LateContext<'_>, hir_id: HirId, if_chain_span: Span) -> bool {
1262 .parent_iter(hir_id)
1265 !matches!(node, Node::Expr(Expr { kind: ExprKind::Block(..), .. }) | Node::Stmt(_))
1267 .map_or(false, |(id, _)| {
1268 is_expn_of(cx.tcx.hir().span(id), "if_chain") != Some(if_chain_span)
1272 /// Checks a trailing slice of statements and expression of a `Block` to see if they are part
1273 /// of the `then {..}` portion of an `if_chain!`
1274 fn is_if_chain_then(stmts: &[Stmt<'_>], expr: Option<&Expr<'_>>, if_chain_span: Span) -> bool {
1275 let span = if let [stmt, ..] = stmts {
1277 } else if let Some(expr) = expr {
1283 is_expn_of(span, "if_chain").map_or(true, |span| span != if_chain_span)
1286 /// Creates a `Span` for `let x = ..;` in an `if_chain!` call.
1287 fn if_chain_local_span(cx: &LateContext<'_>, local: &Local<'_>, if_chain_span: Span) -> Span {
1288 let mut span = local.pat.span;
1289 if let Some(init) = local.init {
1290 span = span.to(init.span);
1292 span.adjust(if_chain_span.ctxt().outer_expn());
1293 let sm = cx.sess().source_map();
1294 let span = sm.span_extend_to_prev_str(span, "let", false);
1295 let span = sm.span_extend_to_next_char(span, ';', false);
1297 span.lo() - BytePos(3),
1298 span.hi() + BytePos(1),