1 use crate::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 is_else_clause, is_expn_of, match_def_path, match_qpath, method_calls, path_to_res, paths, run_lints, SpanlessEq,
8 use if_chain::if_chain;
9 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, ModKind, NodeId};
10 use rustc_ast::visit::FnKind;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::Applicability;
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::hir_id::CRATE_HIR_ID;
17 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
19 BinOpKind, Block, Crate, Expr, ExprKind, HirId, Item, Local, MatchSource, MutTy, Mutability, Node, Path, Stmt,
20 StmtKind, Ty, TyKind, UnOp,
22 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
23 use rustc_middle::hir::map::Map;
24 use rustc_middle::mir::interpret::ConstValue;
26 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
27 use rustc_span::source_map::Spanned;
28 use rustc_span::symbol::{Symbol, SymbolStr};
29 use rustc_span::{BytePos, Span};
30 use rustc_typeck::hir_ty_to_ty;
32 use std::borrow::{Borrow, Cow};
34 declare_clippy_lint! {
35 /// **What it does:** Checks for various things we like to keep tidy in clippy.
37 /// **Why is this bad?** We like to pretend we're an example of tidy code.
39 /// **Known problems:** None.
41 /// **Example:** Wrong ordering of the util::paths constants.
42 pub CLIPPY_LINTS_INTERNAL,
44 "various things that will negatively affect your clippy experience"
47 declare_clippy_lint! {
48 /// **What it does:** Ensures every lint is associated to a `LintPass`.
50 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
51 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
52 /// know the name of the lint.
54 /// **Known problems:** Only checks for lints associated using the
55 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
59 /// declare_lint! { pub LINT_1, ... }
60 /// declare_lint! { pub LINT_2, ... }
61 /// declare_lint! { pub FORGOTTEN_LINT, ... }
63 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
64 /// // missing FORGOTTEN_LINT
66 pub LINT_WITHOUT_LINT_PASS,
68 "declaring a lint without associating it in a LintPass"
71 declare_clippy_lint! {
72 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
73 /// variant of the function.
75 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
76 /// warning/error messages.
78 /// **Known problems:** None.
83 /// cx.span_lint(LINT_NAME, "message");
88 /// utils::span_lint(cx, LINT_NAME, "message");
90 pub COMPILER_LINT_FUNCTIONS,
92 "usage of the lint functions of the compiler instead of the utils::* variant"
95 declare_clippy_lint! {
96 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
97 /// the `cx.outer_expn_data()`
99 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
101 /// **Known problems:** None.
106 /// expr.span.ctxt().outer().expn_data()
111 /// expr.span.ctxt().outer_expn_data()
113 pub OUTER_EXPN_EXPN_DATA,
115 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
118 declare_clippy_lint! {
119 /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
120 /// error message by calling `panic`.
122 /// **Why is this bad?** ICE in large quantities can damage your teeth
124 /// **Known problems:** None
133 "this message should not appear anywhere as we ICE before and don't emit the lint"
136 declare_clippy_lint! {
137 /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
138 /// i.e. `default lint description`.
140 /// **Why is this bad?** Indicates that the lint is not finished.
142 /// **Known problems:** None
147 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
152 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
156 "found 'default lint description' in a lint declaration"
159 declare_clippy_lint! {
160 /// **What it does:** Lints `span_lint_and_then` function calls, where the
161 /// closure argument has only one statement and that statement is a method
162 /// call to `span_suggestion`, `span_help`, `span_note` (using the same
163 /// span), `help` or `note`.
165 /// These usages of `span_lint_and_then` should be replaced with one of the
166 /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
167 /// `span_lint_and_note`.
169 /// **Why is this bad?** Using the wrapper `span_lint_and_*` functions, is more
170 /// convenient, readable and less error prone.
172 /// **Known problems:** None
177 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
178 /// diag.span_suggestion(
181 /// sugg.to_string(),
182 /// Applicability::MachineApplicable,
185 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
186 /// diag.span_help(expr.span, help_msg);
188 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
189 /// diag.help(help_msg);
191 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
192 /// diag.span_note(expr.span, note_msg);
194 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
195 /// diag.note(note_msg);
201 /// span_lint_and_sugg(
207 /// sugg.to_string(),
208 /// Applicability::MachineApplicable,
210 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
211 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
212 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
213 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
215 pub COLLAPSIBLE_SPAN_LINT_CALLS,
217 "found collapsible `span_lint_and_then` calls"
220 declare_clippy_lint! {
221 /// **What it does:** Checks for calls to `utils::match_type()` on a type diagnostic item
222 /// and suggests to use `utils::is_type_diagnostic_item()` instead.
224 /// **Why is this bad?** `utils::is_type_diagnostic_item()` does not require hardcoded paths.
226 /// **Known problems:** None.
231 /// utils::match_type(cx, ty, &paths::VEC)
236 /// utils::is_type_diagnostic_item(cx, ty, sym::vec_type)
238 pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
240 "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
243 declare_clippy_lint! {
244 /// **What it does:**
245 /// Checks the paths module for invalid paths.
247 /// **Why is this bad?**
248 /// It indicates a bug in the code.
250 /// **Known problems:** None.
252 /// **Example:** None.
258 declare_clippy_lint! {
259 /// **What it does:**
260 /// Checks for interning symbols that have already been pre-interned and defined as constants.
262 /// **Why is this bad?**
263 /// It's faster and easier to use the symbol constant.
265 /// **Known problems:** None.
270 /// let _ = sym!(f32);
275 /// let _ = sym::f32;
277 pub INTERNING_DEFINED_SYMBOL,
279 "interning a symbol that is pre-interned and defined as a constant"
282 declare_clippy_lint! {
283 /// **What it does:** Checks for unnecessary conversion from Symbol to a string.
285 /// **Why is this bad?** It's faster use symbols directly intead of strings.
287 /// **Known problems:** None.
292 /// symbol.as_str() == "clippy";
297 /// symbol == sym::clippy;
299 pub UNNECESSARY_SYMBOL_STR,
301 "unnecessary conversion between Symbol and string"
304 declare_clippy_lint! {
305 /// Finds unidiomatic usage of `if_chain!`
308 "non-idiomatic `if_chain!` usage"
311 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
313 impl EarlyLintPass for ClippyLintsInternal {
314 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
315 if let Some(utils) = krate.items.iter().find(|item| item.ident.name.as_str() == "utils") {
316 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
317 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
318 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
319 let mut last_name: Option<SymbolStr> = None;
321 let name = item.ident.as_str();
322 if let Some(ref last_name) = last_name {
323 if **last_name > *name {
326 CLIPPY_LINTS_INTERNAL,
328 "this constant should be before the previous constant due to lexical \
333 last_name = Some(name);
342 #[derive(Clone, Debug, Default)]
343 pub struct LintWithoutLintPass {
344 declared_lints: FxHashMap<Symbol, Span>,
345 registered_lints: FxHashSet<Symbol>,
348 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
350 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
351 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
352 if !run_lints(cx, &[DEFAULT_LINT], item.hir_id()) {
356 if let hir::ItemKind::Static(ty, Mutability::Not, body_id) = item.kind {
357 if is_lint_ref_type(cx, ty) {
358 let expr = &cx.tcx.hir().body(body_id).value;
360 if let ExprKind::AddrOf(_, _, inner_exp) = expr.kind;
361 if let ExprKind::Struct(_, fields, _) = inner_exp.kind;
364 .find(|f| f.ident.as_str() == "desc")
365 .expect("lints must have a description field");
366 if let ExprKind::Lit(Spanned {
367 node: LitKind::Str(ref sym, _),
369 }) = field.expr.kind;
370 if sym.as_str() == "default lint description";
377 &format!("the lint `{}` has the default lint description", item.ident.name),
381 self.declared_lints.insert(item.ident.name, item.span);
383 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
384 || is_expn_of(item.span, "declare_lint_pass").is_some()
386 if let hir::ItemKind::Impl(hir::Impl {
388 items: impl_item_refs,
392 let mut collector = LintCollector {
393 output: &mut self.registered_lints,
396 let body_id = cx.tcx.hir().body_owned_by(
399 .find(|iiref| iiref.ident.as_str() == "get_lints")
400 .expect("LintPass needs to implement get_lints")
404 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
409 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
410 if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
414 for (lint_name, &lint_span) in &self.declared_lints {
415 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
416 // file points to "<rustc macros>".
417 // `compiletest-rs` thinks that's an error in a different file and
418 // just ignores it. This causes the test in compile-fail/lint_pass
419 // not able to capture the error.
420 // Therefore, we need to climb the macro expansion tree and find the
421 // actual span that invoked `declare_tool_lint!`:
422 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
424 if !self.registered_lints.contains(lint_name) {
427 LINT_WITHOUT_LINT_PASS,
429 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
436 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
441 mutbl: Mutability::Not,
445 if let TyKind::Path(ref path) = inner.kind {
446 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
447 return match_def_path(cx, def_id, &paths::LINT);
455 struct LintCollector<'a, 'tcx> {
456 output: &'a mut FxHashSet<Symbol>,
457 cx: &'a LateContext<'tcx>,
460 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
461 type Map = Map<'tcx>;
463 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
464 if path.segments.len() == 1 {
465 self.output.insert(path.segments[0].ident.name);
469 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
470 NestedVisitorMap::All(self.cx.tcx.hir())
474 #[derive(Clone, Default)]
475 pub struct CompilerLintFunctions {
476 map: FxHashMap<&'static str, &'static str>,
479 impl CompilerLintFunctions {
481 pub fn new() -> Self {
482 let mut map = FxHashMap::default();
483 map.insert("span_lint", "utils::span_lint");
484 map.insert("struct_span_lint", "utils::span_lint");
485 map.insert("lint", "utils::span_lint");
486 map.insert("span_lint_note", "utils::span_lint_and_note");
487 map.insert("span_lint_help", "utils::span_lint_and_help");
492 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
494 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
495 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
496 if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
501 if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
502 let fn_name = path.ident;
503 if let Some(sugg) = self.map.get(&*fn_name.as_str());
504 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
505 if match_type(cx, ty, &paths::EARLY_CONTEXT)
506 || match_type(cx, ty, &paths::LATE_CONTEXT);
510 COMPILER_LINT_FUNCTIONS,
512 "usage of a compiler lint function",
514 &format!("please use the Clippy variant of this function: `{}`", sugg),
521 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
523 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
524 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
525 if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
529 let (method_names, arg_lists, spans) = method_calls(expr, 2);
530 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
531 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
533 if let ["expn_data", "outer_expn"] = method_names.as_slice();
534 let args = arg_lists[1];
536 let self_arg = &args[0];
537 let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
538 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
542 OUTER_EXPN_EXPN_DATA,
543 spans[1].with_hi(expr.span.hi()),
544 "usage of `outer_expn().expn_data()`",
546 "outer_expn_data()".to_string(),
547 Applicability::MachineApplicable,
554 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
556 impl EarlyLintPass for ProduceIce {
557 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
558 if is_trigger_fn(fn_kind) {
559 panic!("Would you like some help with that?");
564 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
566 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
567 FnKind::Closure(..) => false,
571 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
573 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
574 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
575 if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
580 if let ExprKind::Call(func, and_then_args) = expr.kind;
581 if let ExprKind::Path(ref path) = func.kind;
582 if match_qpath(path, &["span_lint_and_then"]);
583 if and_then_args.len() == 5;
584 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
585 let body = cx.tcx.hir().body(*body_id);
586 if let ExprKind::Block(block, _) = &body.value.kind;
587 let stmts = &block.stmts;
588 if stmts.len() == 1 && block.expr.is_none();
589 if let StmtKind::Semi(only_expr) = &stmts[0].kind;
590 if let ExprKind::MethodCall(ps, _, span_call_args, _) = &only_expr.kind;
592 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
593 let mut sle = SpanlessEq::new(cx).deny_side_effects();
594 match &*ps.ident.as_str() {
595 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
596 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
598 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
599 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
600 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
602 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
603 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
604 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
607 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
608 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
611 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
612 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
621 struct AndThenSnippets<'a> {
628 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
629 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
630 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
631 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
632 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
642 struct SpanSuggestionSnippets<'a> {
645 applicability: Cow<'a, str>,
648 fn span_suggestion_snippets<'a, 'hir>(
649 cx: &LateContext<'_>,
650 span_call_args: &'hir [Expr<'hir>],
651 ) -> SpanSuggestionSnippets<'a> {
652 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
653 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
654 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
656 SpanSuggestionSnippets {
659 applicability: applicability_snippet,
663 fn suggest_suggestion(
664 cx: &LateContext<'_>,
666 and_then_snippets: &AndThenSnippets<'_>,
667 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
671 COLLAPSIBLE_SPAN_LINT_CALLS,
673 "this call is collapsible",
676 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
677 and_then_snippets.cx,
678 and_then_snippets.lint,
679 and_then_snippets.span,
680 and_then_snippets.msg,
681 span_suggestion_snippets.help,
682 span_suggestion_snippets.sugg,
683 span_suggestion_snippets.applicability
685 Applicability::MachineApplicable,
690 cx: &LateContext<'_>,
692 and_then_snippets: &AndThenSnippets<'_>,
696 let option_span = if with_span {
697 format!("Some({})", and_then_snippets.span)
704 COLLAPSIBLE_SPAN_LINT_CALLS,
706 "this call is collapsible",
709 "span_lint_and_help({}, {}, {}, {}, {}, {})",
710 and_then_snippets.cx,
711 and_then_snippets.lint,
712 and_then_snippets.span,
713 and_then_snippets.msg,
717 Applicability::MachineApplicable,
722 cx: &LateContext<'_>,
724 and_then_snippets: &AndThenSnippets<'_>,
728 let note_span = if with_span {
729 format!("Some({})", and_then_snippets.span)
736 COLLAPSIBLE_SPAN_LINT_CALLS,
738 "this call is collspible",
741 "span_lint_and_note({}, {}, {}, {}, {}, {})",
742 and_then_snippets.cx,
743 and_then_snippets.lint,
744 and_then_snippets.span,
745 and_then_snippets.msg,
749 Applicability::MachineApplicable,
753 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
755 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
756 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
757 if !run_lints(cx, &[MATCH_TYPE_ON_DIAGNOSTIC_ITEM], expr.hir_id) {
762 // Check if this is a call to utils::match_type()
763 if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
764 if let ExprKind::Path(fn_qpath) = &fn_path.kind;
765 if match_qpath(fn_qpath, &["utils", "match_type"]);
766 // Extract the path to the matched type
767 if let Some(segments) = path_to_matched_type(cx, ty_path);
768 let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
769 if let Some(ty_did) = path_to_res(cx, &segments[..]).opt_def_id();
770 // Check if the matched type is a diagnostic item
771 let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
772 if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
774 let cx_snippet = snippet(cx, context.span, "_");
775 let ty_snippet = snippet(cx, ty.span, "_");
779 MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
781 "usage of `utils::match_type()` on a type diagnostic item",
783 format!("utils::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
784 Applicability::MaybeIncorrect,
791 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
792 use rustc_hir::ItemKind;
795 ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
796 ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
797 Res::Local(hir_id) => {
798 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
799 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
800 if let Some(init) = local.init {
801 return path_to_matched_type(cx, init);
805 Res::Def(DefKind::Const | DefKind::Static, def_id) => {
806 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
807 if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
808 let body = cx.tcx.hir().body(body_id);
809 return path_to_matched_type(cx, &body.value);
815 ExprKind::Array(exprs) => {
816 let segments: Vec<SymbolStr> = exprs
819 if let ExprKind::Lit(lit) = &expr.kind {
820 if let LitKind::Str(sym, _) = lit.node {
821 return Some(sym.as_str());
829 if segments.len() == exprs.len() {
830 return Some(segments);
839 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
840 // module. That's all it does and all it needs to do.
841 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
842 if path_to_res(cx, path) != Res::Err {
846 // Some implementations can't be found by `path_to_res`, particularly inherent
847 // implementations of native types. Check lang items.
848 let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
849 let lang_items = cx.tcx.lang_items();
850 for item_def_id in lang_items.items().iter().flatten() {
851 let lang_item_path = cx.get_def_path(*item_def_id);
852 if path_syms.starts_with(&lang_item_path) {
853 if let [item] = &path_syms[lang_item_path.len()..] {
854 for child in cx.tcx.item_children(*item_def_id) {
855 if child.ident.name == *item {
866 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
868 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
869 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
870 let local_def_id = &cx.tcx.parent_module(item.hir_id());
871 let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
873 if mod_name.as_str() == "paths";
874 if let hir::ItemKind::Const(ty, body_id) = item.kind;
875 let ty = hir_ty_to_ty(cx.tcx, ty);
876 if let ty::Array(el_ty, _) = &ty.kind();
877 if let ty::Ref(_, el_ty, _) = &el_ty.kind();
879 let body = cx.tcx.hir().body(body_id);
880 let typeck_results = cx.tcx.typeck_body(body_id);
881 if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
882 let path: Vec<&str> = path.iter().map(|x| {
883 if let Constant::Str(s) = x {
886 // We checked the type of the constant above
890 if !check_path(cx, &path[..]);
892 span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
899 pub struct InterningDefinedSymbol {
900 // Maps the symbol value to the constant DefId.
901 symbol_map: FxHashMap<u32, DefId>,
904 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
906 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
907 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
908 if !self.symbol_map.is_empty() {
912 for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
913 if let Some(def_id) = path_to_res(cx, module).opt_def_id() {
914 for item in cx.tcx.item_children(def_id).iter() {
916 if let Res::Def(DefKind::Const, item_def_id) = item.res;
917 let ty = cx.tcx.type_of(item_def_id);
918 if match_type(cx, ty, &paths::SYMBOL);
919 if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
920 if let Ok(value) = value.to_u32();
922 self.symbol_map.insert(value, item_def_id);
930 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
932 if let ExprKind::Call(func, [arg]) = &expr.kind;
933 if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
934 if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
935 if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
936 let value = Symbol::intern(&arg).as_u32();
937 if let Some(&def_id) = self.symbol_map.get(&value);
941 INTERNING_DEFINED_SYMBOL,
942 is_expn_of(expr.span, "sym").unwrap_or(expr.span),
943 "interning a defined symbol",
945 cx.tcx.def_path_str(def_id),
946 Applicability::MachineApplicable,
950 if let ExprKind::Binary(op, left, right) = expr.kind {
951 if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
953 (left, self.symbol_str_expr(left, cx)),
954 (right, self.symbol_str_expr(right, cx)),
957 // both operands are a symbol string
958 [(_, Some(left)), (_, Some(right))] => {
961 UNNECESSARY_SYMBOL_STR,
963 "unnecessary `Symbol` to string conversion",
967 left.as_symbol_snippet(cx),
969 right.as_symbol_snippet(cx),
971 Applicability::MachineApplicable,
974 // one of the operands is a symbol string
975 [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
976 // creating an owned string for comparison
977 if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
980 UNNECESSARY_SYMBOL_STR,
982 "unnecessary string allocation",
984 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
985 Applicability::MachineApplicable,
990 [(_, None), (_, None)] => {},
997 impl InterningDefinedSymbol {
998 fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
999 static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
1000 static SYMBOL_STR_PATHS: &[&[&str]] = &[
1001 &paths::SYMBOL_AS_STR,
1002 &paths::SYMBOL_TO_IDENT_STRING,
1003 &paths::TO_STRING_METHOD,
1005 // SymbolStr might be de-referenced: `&*symbol.as_str()`
1006 let call = if_chain! {
1007 if let ExprKind::AddrOf(_, _, e) = expr.kind;
1008 if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
1009 then { e } else { expr }
1013 if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1014 if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1015 let ty = cx.typeck_results().expr_ty(item);
1016 // ...on either an Ident or a Symbol
1017 if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1019 } else if match_type(cx, ty, &paths::IDENT) {
1024 // ...which converts it to a string
1025 let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1026 if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1028 let is_to_owned = path.last().unwrap().ends_with("string");
1029 return Some(SymbolStrExpr::Expr {
1036 // is a string constant
1037 if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1038 let value = Symbol::intern(&s).as_u32();
1039 // ...which matches a symbol constant
1040 if let Some(&def_id) = self.symbol_map.get(&value) {
1041 return Some(SymbolStrExpr::Const(def_id));
1048 enum SymbolStrExpr<'tcx> {
1049 /// a string constant with a corresponding symbol constant
1051 /// a "symbol to string" expression like `symbol.as_str()`
1053 /// part that evaluates to `Symbol` or `Ident`
1054 item: &'tcx Expr<'tcx>,
1056 /// whether an owned `String` is created like `to_ident_string()`
1061 impl<'tcx> SymbolStrExpr<'tcx> {
1062 /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1063 fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1065 Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1066 Self::Expr { item, is_ident, .. } => {
1067 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1070 snip.to_mut().push_str(".name");
1078 declare_lint_pass!(IfChainStyle => [IF_CHAIN_STYLE]);
1080 impl<'tcx> LateLintPass<'tcx> for IfChainStyle {
1081 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
1082 let (local, after, if_chain_span) = if_chain! {
1083 if let [Stmt { kind: StmtKind::Local(local), .. }, after @ ..] = block.stmts;
1084 if let Some(if_chain_span) = is_expn_of(block.span, "if_chain");
1085 then { (local, after, if_chain_span) } else { return }
1087 if is_first_if_chain_expr(cx, block.hir_id, if_chain_span) {
1091 if_chain_local_span(cx, local, if_chain_span),
1092 "`let` expression should be above the `if_chain!`",
1094 } else if local.span.ctxt() == block.span.ctxt() && is_if_chain_then(after, block.expr, if_chain_span) {
1098 if_chain_local_span(cx, local, if_chain_span),
1099 "`let` expression should be inside `then { .. }`",
1104 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1105 let (cond, then, els) = match expr.kind {
1106 ExprKind::If(cond, then, els) => (Some(cond), then, els.is_some()),
1110 MatchSource::IfLetDesugar {
1111 contains_else_clause: els,
1113 ) => (None, arm.body, els),
1116 let then_block = match then.kind {
1117 ExprKind::Block(block, _) => block,
1120 let if_chain_span = is_expn_of(expr.span, "if_chain");
1122 check_nested_if_chains(cx, expr, then_block, if_chain_span);
1124 let if_chain_span = match if_chain_span {
1128 // check for `if a && b;`
1130 if let Some(cond) = cond;
1131 if let ExprKind::Binary(op, _, _) = cond.kind;
1132 if op.node == BinOpKind::And;
1133 if cx.sess().source_map().is_multiline(cond.span);
1135 span_lint(cx, IF_CHAIN_STYLE, cond.span, "`if a && b;` should be `if a; if b;`");
1138 if is_first_if_chain_expr(cx, expr.hir_id, if_chain_span)
1139 && is_if_chain_then(then_block.stmts, then_block.expr, if_chain_span)
1141 span_lint(cx, IF_CHAIN_STYLE, expr.span, "`if_chain!` only has one `if`")
1146 fn check_nested_if_chains(
1147 cx: &LateContext<'_>,
1149 then_block: &Block<'_>,
1150 if_chain_span: Option<Span>,
1153 let (head, tail) = match *then_block {
1154 Block { stmts, expr: Some(tail), .. } => (stmts, tail),
1158 Stmt { kind: StmtKind::Expr(tail) | StmtKind::Semi(tail), .. }
1165 if matches!(tail.kind,
1166 ExprKind::If(_, _, None)
1167 | ExprKind::Match(.., MatchSource::IfLetDesugar { contains_else_clause: false }));
1168 let sm = cx.sess().source_map();
1171 .all(|stmt| matches!(stmt.kind, StmtKind::Local(..)) && !sm.is_multiline(stmt.span));
1172 if if_chain_span.is_some() || !is_else_clause(cx.tcx, if_expr);
1173 then {} else { return }
1175 let (span, msg) = match (if_chain_span, is_expn_of(tail.span, "if_chain")) {
1176 (None, Some(_)) => (if_expr.span, "this `if` can be part of the inner `if_chain!`"),
1177 (Some(_), None) => (tail.span, "this `if` can be part of the outer `if_chain!`"),
1178 (Some(a), Some(b)) if a != b => (b, "this `if_chain!` can be merged with the outer `if_chain!`"),
1181 span_lint_and_then(cx, IF_CHAIN_STYLE, span, msg, |diag| {
1182 let (span, msg) = match head {
1184 [stmt] => (stmt.span, "this `let` statement can also be in the `if_chain!`"),
1187 "these `let` statements can also be in the `if_chain!`",
1190 diag.span_help(span, msg);
1194 fn is_first_if_chain_expr(cx: &LateContext<'_>, hir_id: HirId, if_chain_span: Span) -> bool {
1197 .parent_iter(hir_id)
1200 !matches!(node, Node::Expr(Expr { kind: ExprKind::Block(..), .. }) | Node::Stmt(_))
1202 .map_or(false, |(id, _)| {
1203 is_expn_of(cx.tcx.hir().span(id), "if_chain") != Some(if_chain_span)
1207 /// Checks a trailing slice of statements and expression of a `Block` to see if they are part
1208 /// of the `then {..}` portion of an `if_chain!`
1209 fn is_if_chain_then(stmts: &[Stmt<'_>], expr: Option<&Expr<'_>>, if_chain_span: Span) -> bool {
1210 let span = if let [stmt, ..] = stmts {
1212 } else if let Some(expr) = expr {
1218 is_expn_of(span, "if_chain").map_or(true, |span| span != if_chain_span)
1221 /// Creates a `Span` for `let x = ..;` in an `if_chain!` call.
1222 fn if_chain_local_span(cx: &LateContext<'_>, local: &Local<'_>, if_chain_span: Span) -> Span {
1223 let mut span = local.pat.span;
1224 if let Some(init) = local.init {
1225 span = span.to(init.span);
1227 span.adjust(if_chain_span.ctxt().outer_expn());
1228 let sm = cx.sess().source_map();
1229 let span = sm.span_extend_to_prev_str(span, "let", false);
1230 let span = sm.span_extend_to_next_char(span, ';', false);
1231 Span::new(span.lo() - BytePos(3), span.hi() + BytePos(1), span.ctxt())