1 use clippy_utils::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
3 use clippy_utils::higher;
4 use clippy_utils::source::snippet;
5 use clippy_utils::ty::match_type;
7 is_else_clause, is_expn_of, is_expr_path_def_path, is_lint_allowed, match_def_path, method_calls, path_to_res,
10 use if_chain::if_chain;
11 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, ModKind, NodeId};
12 use rustc_ast::visit::FnKind;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_errors::Applicability;
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, Crate, Expr, ExprKind, HirId, Item, Local, MutTy, Mutability, Node, Path, Stmt, StmtKind, Ty,
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_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
29 use rustc_span::source_map::Spanned;
30 use rustc_span::symbol::{Symbol, SymbolStr};
31 use rustc_span::{BytePos, Span};
32 use rustc_typeck::hir_ty_to_ty;
34 use std::borrow::{Borrow, Cow};
36 #[cfg(feature = "metadata-collector-lint")]
37 pub mod metadata_collector;
39 declare_clippy_lint! {
41 /// Checks for various things we like to keep tidy in clippy.
43 /// ### Why is this bad?
44 /// We like to pretend we're an example of tidy code.
47 /// Wrong ordering of the util::paths constants.
48 pub CLIPPY_LINTS_INTERNAL,
50 "various things that will negatively affect your clippy experience"
53 declare_clippy_lint! {
55 /// Ensures every lint is associated to a `LintPass`.
57 /// ### Why is this bad?
58 /// The compiler only knows lints via a `LintPass`. Without
59 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
60 /// know the name of the lint.
62 /// ### Known problems
63 /// Only checks for lints associated using the
64 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
68 /// declare_lint! { pub LINT_1, ... }
69 /// declare_lint! { pub LINT_2, ... }
70 /// declare_lint! { pub FORGOTTEN_LINT, ... }
72 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
73 /// // missing FORGOTTEN_LINT
75 pub LINT_WITHOUT_LINT_PASS,
77 "declaring a lint without associating it in a LintPass"
80 declare_clippy_lint! {
82 /// Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
83 /// variant of the function.
85 /// ### Why is this bad?
86 /// The `utils::*` variants also add a link to the Clippy documentation to the
87 /// warning/error messages.
92 /// cx.span_lint(LINT_NAME, "message");
97 /// utils::span_lint(cx, LINT_NAME, "message");
99 pub COMPILER_LINT_FUNCTIONS,
101 "usage of the lint functions of the compiler instead of the utils::* variant"
104 declare_clippy_lint! {
106 /// Checks for calls to `cx.outer().expn_data()` and suggests to use
107 /// the `cx.outer_expn_data()`
109 /// ### Why is this bad?
110 /// `cx.outer_expn_data()` is faster and more concise.
115 /// expr.span.ctxt().outer().expn_data()
120 /// expr.span.ctxt().outer_expn_data()
122 pub OUTER_EXPN_EXPN_DATA,
124 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
127 declare_clippy_lint! {
129 /// Not an actual lint. This lint is only meant for testing our customized internal compiler
130 /// error message by calling `panic`.
132 /// ### Why is this bad?
133 /// ICE in large quantities can damage your teeth
142 "this message should not appear anywhere as we ICE before and don't emit the lint"
145 declare_clippy_lint! {
147 /// Checks for cases of an auto-generated lint without an updated description,
148 /// i.e. `default lint description`.
150 /// ### Why is this bad?
151 /// Indicates that the lint is not finished.
156 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
161 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
165 "found 'default lint description' in a lint declaration"
168 declare_clippy_lint! {
170 /// Lints `span_lint_and_then` function calls, where the
171 /// closure argument has only one statement and that statement is a method
172 /// call to `span_suggestion`, `span_help`, `span_note` (using the same
173 /// span), `help` or `note`.
175 /// These usages of `span_lint_and_then` should be replaced with one of the
176 /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
177 /// `span_lint_and_note`.
179 /// ### Why is this bad?
180 /// Using the wrapper `span_lint_and_*` functions, is more
181 /// convenient, readable and less error prone.
186 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
187 /// diag.span_suggestion(
190 /// sugg.to_string(),
191 /// Applicability::MachineApplicable,
194 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
195 /// diag.span_help(expr.span, help_msg);
197 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
198 /// diag.help(help_msg);
200 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
201 /// diag.span_note(expr.span, note_msg);
203 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
204 /// diag.note(note_msg);
210 /// span_lint_and_sugg(
216 /// sugg.to_string(),
217 /// Applicability::MachineApplicable,
219 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
220 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
221 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
222 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
224 pub COLLAPSIBLE_SPAN_LINT_CALLS,
226 "found collapsible `span_lint_and_then` calls"
229 declare_clippy_lint! {
231 /// Checks for calls to `utils::match_type()` on a type diagnostic item
232 /// and suggests to use `utils::is_type_diagnostic_item()` instead.
234 /// ### Why is this bad?
235 /// `utils::is_type_diagnostic_item()` does not require hardcoded paths.
240 /// utils::match_type(cx, ty, &paths::VEC)
245 /// utils::is_type_diagnostic_item(cx, ty, sym::vec_type)
247 pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
249 "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
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.
276 /// let _ = sym!(f32);
281 /// let _ = sym::f32;
283 pub INTERNING_DEFINED_SYMBOL,
285 "interning a symbol that is pre-interned and defined as a constant"
288 declare_clippy_lint! {
290 /// Checks for unnecessary conversion from Symbol to a string.
292 /// ### Why is this bad?
293 /// It's faster use symbols directly intead of strings.
298 /// symbol.as_str() == "clippy";
303 /// symbol == sym::clippy;
305 pub UNNECESSARY_SYMBOL_STR,
307 "unnecessary conversion between Symbol and string"
310 declare_clippy_lint! {
311 /// Finds unidiomatic usage of `if_chain!`
314 "non-idiomatic `if_chain!` usage"
317 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
319 impl EarlyLintPass for ClippyLintsInternal {
320 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
321 if let Some(utils) = krate.items.iter().find(|item| item.ident.name.as_str() == "utils") {
322 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
323 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
324 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
325 let mut last_name: Option<SymbolStr> = None;
327 let name = item.ident.as_str();
328 if let Some(ref last_name) = last_name {
329 if **last_name > *name {
332 CLIPPY_LINTS_INTERNAL,
334 "this constant should be before the previous constant due to lexical \
339 last_name = Some(name);
348 #[derive(Clone, Debug, Default)]
349 pub struct LintWithoutLintPass {
350 declared_lints: FxHashMap<Symbol, Span>,
351 registered_lints: FxHashSet<Symbol>,
354 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
356 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
357 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
358 if is_lint_allowed(cx, DEFAULT_LINT, item.hir_id()) {
362 if let hir::ItemKind::Static(ty, Mutability::Not, body_id) = item.kind {
363 if is_lint_ref_type(cx, ty) {
364 let expr = &cx.tcx.hir().body(body_id).value;
366 if let ExprKind::AddrOf(_, _, inner_exp) = expr.kind;
367 if let ExprKind::Struct(_, fields, _) = inner_exp.kind;
370 .find(|f| f.ident.as_str() == "desc")
371 .expect("lints must have a description field");
372 if let ExprKind::Lit(Spanned {
373 node: LitKind::Str(ref sym, _),
375 }) = field.expr.kind;
376 if sym.as_str() == "default lint description";
383 &format!("the lint `{}` has the default lint description", item.ident.name),
387 self.declared_lints.insert(item.ident.name, item.span);
389 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
390 || is_expn_of(item.span, "declare_lint_pass").is_some()
392 if let hir::ItemKind::Impl(hir::Impl {
394 items: impl_item_refs,
398 let mut collector = LintCollector {
399 output: &mut self.registered_lints,
402 let body_id = cx.tcx.hir().body_owned_by(
405 .find(|iiref| iiref.ident.as_str() == "get_lints")
406 .expect("LintPass needs to implement get_lints")
410 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
415 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
416 if is_lint_allowed(cx, LINT_WITHOUT_LINT_PASS, CRATE_HIR_ID) {
420 for (lint_name, &lint_span) in &self.declared_lints {
421 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
422 // file points to "<rustc macros>".
423 // `compiletest-rs` thinks that's an error in a different file and
424 // just ignores it. This causes the test in compile-fail/lint_pass
425 // not able to capture the error.
426 // Therefore, we need to climb the macro expansion tree and find the
427 // actual span that invoked `declare_tool_lint!`:
428 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
430 if !self.registered_lints.contains(lint_name) {
433 LINT_WITHOUT_LINT_PASS,
435 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
442 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
447 mutbl: Mutability::Not,
451 if let TyKind::Path(ref path) = inner.kind {
452 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
453 return match_def_path(cx, def_id, &paths::LINT);
461 struct LintCollector<'a, 'tcx> {
462 output: &'a mut FxHashSet<Symbol>,
463 cx: &'a LateContext<'tcx>,
466 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
467 type Map = Map<'tcx>;
469 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
470 if path.segments.len() == 1 {
471 self.output.insert(path.segments[0].ident.name);
475 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
476 NestedVisitorMap::All(self.cx.tcx.hir())
480 #[derive(Clone, Default)]
481 pub struct CompilerLintFunctions {
482 map: FxHashMap<&'static str, &'static str>,
485 impl CompilerLintFunctions {
487 pub fn new() -> Self {
488 let mut map = FxHashMap::default();
489 map.insert("span_lint", "utils::span_lint");
490 map.insert("struct_span_lint", "utils::span_lint");
491 map.insert("lint", "utils::span_lint");
492 map.insert("span_lint_note", "utils::span_lint_and_note");
493 map.insert("span_lint_help", "utils::span_lint_and_help");
498 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
500 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
501 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
502 if is_lint_allowed(cx, COMPILER_LINT_FUNCTIONS, expr.hir_id) {
507 if let ExprKind::MethodCall(path, _, [self_arg, ..], _) = &expr.kind;
508 let fn_name = path.ident;
509 if let Some(sugg) = self.map.get(&*fn_name.as_str());
510 let ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
511 if match_type(cx, ty, &paths::EARLY_CONTEXT)
512 || match_type(cx, ty, &paths::LATE_CONTEXT);
516 COMPILER_LINT_FUNCTIONS,
518 "usage of a compiler lint function",
520 &format!("please use the Clippy variant of this function: `{}`", sugg),
527 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
529 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
530 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
531 if is_lint_allowed(cx, OUTER_EXPN_EXPN_DATA, expr.hir_id) {
535 let (method_names, arg_lists, spans) = method_calls(expr, 2);
536 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
537 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
539 if let ["expn_data", "outer_expn"] = method_names.as_slice();
540 let args = arg_lists[1];
542 let self_arg = &args[0];
543 let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
544 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
548 OUTER_EXPN_EXPN_DATA,
549 spans[1].with_hi(expr.span.hi()),
550 "usage of `outer_expn().expn_data()`",
552 "outer_expn_data()".to_string(),
553 Applicability::MachineApplicable,
560 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
562 impl EarlyLintPass for ProduceIce {
563 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
564 assert!(!is_trigger_fn(fn_kind), "Would you like some help with that?");
568 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
570 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
571 FnKind::Closure(..) => false,
575 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
577 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
578 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
579 if is_lint_allowed(cx, COLLAPSIBLE_SPAN_LINT_CALLS, expr.hir_id) {
584 if let ExprKind::Call(func, and_then_args) = expr.kind;
585 if is_expr_path_def_path(cx, func, &["clippy_utils", "diagnostics", "span_lint_and_then"]);
586 if and_then_args.len() == 5;
587 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
588 let body = cx.tcx.hir().body(*body_id);
589 if let ExprKind::Block(block, _) = &body.value.kind;
590 let stmts = &block.stmts;
591 if stmts.len() == 1 && block.expr.is_none();
592 if let StmtKind::Semi(only_expr) = &stmts[0].kind;
593 if let ExprKind::MethodCall(ps, _, span_call_args, _) = &only_expr.kind;
595 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
596 let mut sle = SpanlessEq::new(cx).deny_side_effects();
597 match &*ps.ident.as_str() {
598 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
599 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
601 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
602 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
603 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
605 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
606 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
607 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
610 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
611 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
614 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
615 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
624 struct AndThenSnippets<'a> {
631 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
632 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
633 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
634 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
635 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
645 struct SpanSuggestionSnippets<'a> {
648 applicability: Cow<'a, str>,
651 fn span_suggestion_snippets<'a, 'hir>(
652 cx: &LateContext<'_>,
653 span_call_args: &'hir [Expr<'hir>],
654 ) -> SpanSuggestionSnippets<'a> {
655 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
656 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
657 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
659 SpanSuggestionSnippets {
662 applicability: applicability_snippet,
666 fn suggest_suggestion(
667 cx: &LateContext<'_>,
669 and_then_snippets: &AndThenSnippets<'_>,
670 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
674 COLLAPSIBLE_SPAN_LINT_CALLS,
676 "this call is collapsible",
679 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
680 and_then_snippets.cx,
681 and_then_snippets.lint,
682 and_then_snippets.span,
683 and_then_snippets.msg,
684 span_suggestion_snippets.help,
685 span_suggestion_snippets.sugg,
686 span_suggestion_snippets.applicability
688 Applicability::MachineApplicable,
693 cx: &LateContext<'_>,
695 and_then_snippets: &AndThenSnippets<'_>,
699 let option_span = if with_span {
700 format!("Some({})", and_then_snippets.span)
707 COLLAPSIBLE_SPAN_LINT_CALLS,
709 "this call is collapsible",
712 "span_lint_and_help({}, {}, {}, {}, {}, {})",
713 and_then_snippets.cx,
714 and_then_snippets.lint,
715 and_then_snippets.span,
716 and_then_snippets.msg,
720 Applicability::MachineApplicable,
725 cx: &LateContext<'_>,
727 and_then_snippets: &AndThenSnippets<'_>,
731 let note_span = if with_span {
732 format!("Some({})", and_then_snippets.span)
739 COLLAPSIBLE_SPAN_LINT_CALLS,
741 "this call is collspible",
744 "span_lint_and_note({}, {}, {}, {}, {}, {})",
745 and_then_snippets.cx,
746 and_then_snippets.lint,
747 and_then_snippets.span,
748 and_then_snippets.msg,
752 Applicability::MachineApplicable,
756 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
758 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
759 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
760 if is_lint_allowed(cx, MATCH_TYPE_ON_DIAGNOSTIC_ITEM, expr.hir_id) {
765 // Check if this is a call to utils::match_type()
766 if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
767 if is_expr_path_def_path(cx, fn_path, &["clippy_utils", "ty", "match_type"]);
768 // Extract the path to the matched type
769 if let Some(segments) = path_to_matched_type(cx, ty_path);
770 let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
771 if let Some(ty_did) = path_to_res(cx, &segments[..]).opt_def_id();
772 // Check if the matched type is a diagnostic item
773 let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
774 if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
776 // TODO: check paths constants from external crates.
777 let cx_snippet = snippet(cx, context.span, "_");
778 let ty_snippet = snippet(cx, ty.span, "_");
782 MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
784 "usage of `clippy_utils::ty::match_type()` on a type diagnostic item",
786 format!("clippy_utils::ty::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
787 Applicability::MaybeIncorrect,
794 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
795 use rustc_hir::ItemKind;
798 ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
799 ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
800 Res::Local(hir_id) => {
801 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
802 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
803 if let Some(init) = local.init {
804 return path_to_matched_type(cx, init);
808 Res::Def(DefKind::Const | DefKind::Static, def_id) => {
809 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
810 if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
811 let body = cx.tcx.hir().body(body_id);
812 return path_to_matched_type(cx, &body.value);
818 ExprKind::Array(exprs) => {
819 let segments: Vec<SymbolStr> = exprs
822 if let ExprKind::Lit(lit) = &expr.kind {
823 if let LitKind::Str(sym, _) = lit.node {
824 return Some(sym.as_str());
832 if segments.len() == exprs.len() {
833 return Some(segments);
842 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
843 // module. That's all it does and all it needs to do.
844 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
845 if path_to_res(cx, path) != Res::Err {
849 // Some implementations can't be found by `path_to_res`, particularly inherent
850 // implementations of native types. Check lang items.
851 let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
852 let lang_items = cx.tcx.lang_items();
853 for item_def_id in lang_items.items().iter().flatten() {
854 let lang_item_path = cx.get_def_path(*item_def_id);
855 if path_syms.starts_with(&lang_item_path) {
856 if let [item] = &path_syms[lang_item_path.len()..] {
857 for child in cx.tcx.item_children(*item_def_id) {
858 if child.ident.name == *item {
869 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
871 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
872 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
873 let local_def_id = &cx.tcx.parent_module(item.hir_id());
874 let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
876 if mod_name.as_str() == "paths";
877 if let hir::ItemKind::Const(ty, body_id) = item.kind;
878 let ty = hir_ty_to_ty(cx.tcx, ty);
879 if let ty::Array(el_ty, _) = &ty.kind();
880 if let ty::Ref(_, el_ty, _) = &el_ty.kind();
882 let body = cx.tcx.hir().body(body_id);
883 let typeck_results = cx.tcx.typeck_body(body_id);
884 if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
885 let path: Vec<&str> = path.iter().map(|x| {
886 if let Constant::Str(s) = x {
889 // We checked the type of the constant above
893 if !check_path(cx, &path[..]);
895 span_lint(cx, INVALID_PATHS, item.span, "invalid path");
902 pub struct InterningDefinedSymbol {
903 // Maps the symbol value to the constant DefId.
904 symbol_map: FxHashMap<u32, DefId>,
907 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
909 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
910 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
911 if !self.symbol_map.is_empty() {
915 for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
916 if let Some(def_id) = path_to_res(cx, module).opt_def_id() {
917 for item in cx.tcx.item_children(def_id).iter() {
919 if let Res::Def(DefKind::Const, item_def_id) = item.res;
920 let ty = cx.tcx.type_of(item_def_id);
921 if match_type(cx, ty, &paths::SYMBOL);
922 if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
923 if let Ok(value) = value.to_u32();
925 self.symbol_map.insert(value, item_def_id);
933 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
935 if let ExprKind::Call(func, [arg]) = &expr.kind;
936 if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
937 if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
938 if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
939 let value = Symbol::intern(&arg).as_u32();
940 if let Some(&def_id) = self.symbol_map.get(&value);
944 INTERNING_DEFINED_SYMBOL,
945 is_expn_of(expr.span, "sym").unwrap_or(expr.span),
946 "interning a defined symbol",
948 cx.tcx.def_path_str(def_id),
949 Applicability::MachineApplicable,
953 if let ExprKind::Binary(op, left, right) = expr.kind {
954 if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
956 (left, self.symbol_str_expr(left, cx)),
957 (right, self.symbol_str_expr(right, cx)),
960 // both operands are a symbol string
961 [(_, Some(left)), (_, Some(right))] => {
964 UNNECESSARY_SYMBOL_STR,
966 "unnecessary `Symbol` to string conversion",
970 left.as_symbol_snippet(cx),
972 right.as_symbol_snippet(cx),
974 Applicability::MachineApplicable,
977 // one of the operands is a symbol string
978 [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
979 // creating an owned string for comparison
980 if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
983 UNNECESSARY_SYMBOL_STR,
985 "unnecessary string allocation",
987 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
988 Applicability::MachineApplicable,
993 [(_, None), (_, None)] => {},
1000 impl InterningDefinedSymbol {
1001 fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
1002 static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
1003 static SYMBOL_STR_PATHS: &[&[&str]] = &[
1004 &paths::SYMBOL_AS_STR,
1005 &paths::SYMBOL_TO_IDENT_STRING,
1006 &paths::TO_STRING_METHOD,
1008 // SymbolStr might be de-referenced: `&*symbol.as_str()`
1009 let call = if_chain! {
1010 if let ExprKind::AddrOf(_, _, e) = expr.kind;
1011 if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
1012 then { e } else { expr }
1016 if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1017 if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1018 let ty = cx.typeck_results().expr_ty(item);
1019 // ...on either an Ident or a Symbol
1020 if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1022 } else if match_type(cx, ty, &paths::IDENT) {
1027 // ...which converts it to a string
1028 let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1029 if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1031 let is_to_owned = path.last().unwrap().ends_with("string");
1032 return Some(SymbolStrExpr::Expr {
1039 // is a string constant
1040 if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1041 let value = Symbol::intern(&s).as_u32();
1042 // ...which matches a symbol constant
1043 if let Some(&def_id) = self.symbol_map.get(&value) {
1044 return Some(SymbolStrExpr::Const(def_id));
1051 enum SymbolStrExpr<'tcx> {
1052 /// a string constant with a corresponding symbol constant
1054 /// a "symbol to string" expression like `symbol.as_str()`
1056 /// part that evaluates to `Symbol` or `Ident`
1057 item: &'tcx Expr<'tcx>,
1059 /// whether an owned `String` is created like `to_ident_string()`
1064 impl<'tcx> SymbolStrExpr<'tcx> {
1065 /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1066 fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1068 Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1069 Self::Expr { item, is_ident, .. } => {
1070 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1073 snip.to_mut().push_str(".name");
1081 declare_lint_pass!(IfChainStyle => [IF_CHAIN_STYLE]);
1083 impl<'tcx> LateLintPass<'tcx> for IfChainStyle {
1084 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
1085 let (local, after, if_chain_span) = if_chain! {
1086 if let [Stmt { kind: StmtKind::Local(local), .. }, after @ ..] = block.stmts;
1087 if let Some(if_chain_span) = is_expn_of(block.span, "if_chain");
1088 then { (local, after, if_chain_span) } else { return }
1090 if is_first_if_chain_expr(cx, block.hir_id, if_chain_span) {
1094 if_chain_local_span(cx, local, if_chain_span),
1095 "`let` expression should be above the `if_chain!`",
1097 } else if local.span.ctxt() == block.span.ctxt() && is_if_chain_then(after, block.expr, if_chain_span) {
1101 if_chain_local_span(cx, local, if_chain_span),
1102 "`let` expression should be inside `then { .. }`",
1107 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1108 let (cond, then, els) = if let Some(higher::IfOrIfLet { cond, r#else, then }) = higher::IfOrIfLet::hir(expr) {
1109 (cond, then, r#else.is_some())
1113 let then_block = match then.kind {
1114 ExprKind::Block(block, _) => block,
1117 let if_chain_span = is_expn_of(expr.span, "if_chain");
1119 check_nested_if_chains(cx, expr, then_block, if_chain_span);
1121 let if_chain_span = match if_chain_span {
1125 // check for `if a && b;`
1127 if let ExprKind::Binary(op, _, _) = cond.kind;
1128 if op.node == BinOpKind::And;
1129 if cx.sess().source_map().is_multiline(cond.span);
1131 span_lint(cx, IF_CHAIN_STYLE, cond.span, "`if a && b;` should be `if a; if b;`");
1134 if is_first_if_chain_expr(cx, expr.hir_id, if_chain_span)
1135 && is_if_chain_then(then_block.stmts, then_block.expr, if_chain_span)
1137 span_lint(cx, IF_CHAIN_STYLE, expr.span, "`if_chain!` only has one `if`");
1142 fn check_nested_if_chains(
1143 cx: &LateContext<'_>,
1145 then_block: &Block<'_>,
1146 if_chain_span: Option<Span>,
1149 let (head, tail) = match *then_block {
1150 Block { stmts, expr: Some(tail), .. } => (stmts, tail),
1154 Stmt { kind: StmtKind::Expr(tail) | StmtKind::Semi(tail), .. }
1161 if let Some(higher::IfOrIfLet { r#else: None, .. }) = higher::IfOrIfLet::hir(tail);
1162 let sm = cx.sess().source_map();
1165 .all(|stmt| matches!(stmt.kind, StmtKind::Local(..)) && !sm.is_multiline(stmt.span));
1166 if if_chain_span.is_some() || !is_else_clause(cx.tcx, if_expr);
1167 then {} else { return }
1169 let (span, msg) = match (if_chain_span, is_expn_of(tail.span, "if_chain")) {
1170 (None, Some(_)) => (if_expr.span, "this `if` can be part of the inner `if_chain!`"),
1171 (Some(_), None) => (tail.span, "this `if` can be part of the outer `if_chain!`"),
1172 (Some(a), Some(b)) if a != b => (b, "this `if_chain!` can be merged with the outer `if_chain!`"),
1175 span_lint_and_then(cx, IF_CHAIN_STYLE, span, msg, |diag| {
1176 let (span, msg) = match head {
1178 [stmt] => (stmt.span, "this `let` statement can also be in the `if_chain!`"),
1181 "these `let` statements can also be in the `if_chain!`",
1184 diag.span_help(span, msg);
1188 fn is_first_if_chain_expr(cx: &LateContext<'_>, hir_id: HirId, if_chain_span: Span) -> bool {
1191 .parent_iter(hir_id)
1194 !matches!(node, Node::Expr(Expr { kind: ExprKind::Block(..), .. }) | Node::Stmt(_))
1196 .map_or(false, |(id, _)| {
1197 is_expn_of(cx.tcx.hir().span(id), "if_chain") != Some(if_chain_span)
1201 /// Checks a trailing slice of statements and expression of a `Block` to see if they are part
1202 /// of the `then {..}` portion of an `if_chain!`
1203 fn is_if_chain_then(stmts: &[Stmt<'_>], expr: Option<&Expr<'_>>, if_chain_span: Span) -> bool {
1204 let span = if let [stmt, ..] = stmts {
1206 } else if let Some(expr) = expr {
1212 is_expn_of(span, "if_chain").map_or(true, |span| span != if_chain_span)
1215 /// Creates a `Span` for `let x = ..;` in an `if_chain!` call.
1216 fn if_chain_local_span(cx: &LateContext<'_>, local: &Local<'_>, if_chain_span: Span) -> Span {
1217 let mut span = local.pat.span;
1218 if let Some(init) = local.init {
1219 span = span.to(init.span);
1221 span.adjust(if_chain_span.ctxt().outer_expn());
1222 let sm = cx.sess().source_map();
1223 let span = sm.span_extend_to_prev_str(span, "let", false);
1224 let span = sm.span_extend_to_next_char(span, ';', false);
1226 span.lo() - BytePos(3),
1227 span.hi() + BytePos(1),