1 use crate::consts::{constant_simple, Constant};
3 is_expn_of, match_def_path, match_qpath, match_type, method_calls, path_to_res, paths, run_lints, snippet,
4 span_lint, span_lint_and_help, span_lint_and_sugg, SpanlessEq,
6 use if_chain::if_chain;
7 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, NodeId};
8 use rustc_ast::visit::FnKind;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_errors::Applicability;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::DefId;
14 use rustc_hir::hir_id::CRATE_HIR_ID;
15 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
17 BinOpKind, Crate, Expr, ExprKind, HirId, Item, MutTy, Mutability, Node, Path, StmtKind, Ty, TyKind, UnOp,
19 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass};
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::mir::interpret::ConstValue;
23 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
24 use rustc_span::source_map::{Span, Spanned};
25 use rustc_span::symbol::{Symbol, SymbolStr};
26 use rustc_typeck::hir_ty_to_ty;
28 use std::borrow::{Borrow, Cow};
30 declare_clippy_lint! {
31 /// **What it does:** Checks for various things we like to keep tidy in clippy.
33 /// **Why is this bad?** We like to pretend we're an example of tidy code.
35 /// **Known problems:** None.
37 /// **Example:** Wrong ordering of the util::paths constants.
38 pub CLIPPY_LINTS_INTERNAL,
40 "various things that will negatively affect your clippy experience"
43 declare_clippy_lint! {
44 /// **What it does:** Ensures every lint is associated to a `LintPass`.
46 /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
47 /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
48 /// know the name of the lint.
50 /// **Known problems:** Only checks for lints associated using the
51 /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
55 /// declare_lint! { pub LINT_1, ... }
56 /// declare_lint! { pub LINT_2, ... }
57 /// declare_lint! { pub FORGOTTEN_LINT, ... }
59 /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
60 /// // missing FORGOTTEN_LINT
62 pub LINT_WITHOUT_LINT_PASS,
64 "declaring a lint without associating it in a LintPass"
67 declare_clippy_lint! {
68 /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
69 /// variant of the function.
71 /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
72 /// warning/error messages.
74 /// **Known problems:** None.
79 /// cx.span_lint(LINT_NAME, "message");
84 /// utils::span_lint(cx, LINT_NAME, "message");
86 pub COMPILER_LINT_FUNCTIONS,
88 "usage of the lint functions of the compiler instead of the utils::* variant"
91 declare_clippy_lint! {
92 /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
93 /// the `cx.outer_expn_data()`
95 /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
97 /// **Known problems:** None.
102 /// expr.span.ctxt().outer().expn_data()
107 /// expr.span.ctxt().outer_expn_data()
109 pub OUTER_EXPN_EXPN_DATA,
111 "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
114 declare_clippy_lint! {
115 /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
116 /// error message by calling `panic`.
118 /// **Why is this bad?** ICE in large quantities can damage your teeth
120 /// **Known problems:** None
129 "this message should not appear anywhere as we ICE before and don't emit the lint"
132 declare_clippy_lint! {
133 /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
134 /// i.e. `default lint description`.
136 /// **Why is this bad?** Indicates that the lint is not finished.
138 /// **Known problems:** None
143 /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
148 /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
152 "found 'default lint description' in a lint declaration"
155 declare_clippy_lint! {
156 /// **What it does:** Lints `span_lint_and_then` function calls, where the
157 /// closure argument has only one statement and that statement is a method
158 /// call to `span_suggestion`, `span_help`, `span_note` (using the same
159 /// span), `help` or `note`.
161 /// These usages of `span_lint_and_then` should be replaced with one of the
162 /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
163 /// `span_lint_and_note`.
165 /// **Why is this bad?** Using the wrapper `span_lint_and_*` functions, is more
166 /// convenient, readable and less error prone.
168 /// **Known problems:** None
173 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
174 /// diag.span_suggestion(
177 /// sugg.to_string(),
178 /// Applicability::MachineApplicable,
181 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
182 /// diag.span_help(expr.span, help_msg);
184 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
185 /// diag.help(help_msg);
187 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
188 /// diag.span_note(expr.span, note_msg);
190 /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
191 /// diag.note(note_msg);
197 /// span_lint_and_sugg(
203 /// sugg.to_string(),
204 /// Applicability::MachineApplicable,
206 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
207 /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
208 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
209 /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
211 pub COLLAPSIBLE_SPAN_LINT_CALLS,
213 "found collapsible `span_lint_and_then` calls"
216 declare_clippy_lint! {
217 /// **What it does:** Checks for calls to `utils::match_type()` on a type diagnostic item
218 /// and suggests to use `utils::is_type_diagnostic_item()` instead.
220 /// **Why is this bad?** `utils::is_type_diagnostic_item()` does not require hardcoded paths.
222 /// **Known problems:** None.
227 /// utils::match_type(cx, ty, &paths::VEC)
232 /// utils::is_type_diagnostic_item(cx, ty, sym::vec_type)
234 pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
236 "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
239 declare_clippy_lint! {
240 /// **What it does:**
241 /// Checks the paths module for invalid paths.
243 /// **Why is this bad?**
244 /// It indicates a bug in the code.
246 /// **Known problems:** None.
248 /// **Example:** None.
254 declare_clippy_lint! {
255 /// **What it does:**
256 /// Checks for interning symbols that have already been pre-interned and defined as constants.
258 /// **Why is this bad?**
259 /// It's faster and easier to use the symbol constant.
261 /// **Known problems:** None.
266 /// let _ = sym!(f32);
271 /// let _ = sym::f32;
273 pub INTERNING_DEFINED_SYMBOL,
275 "interning a symbol that is pre-interned and defined as a constant"
278 declare_clippy_lint! {
279 /// **What it does:** Checks for unnecessary conversion from Symbol to a string.
281 /// **Why is this bad?** It's faster use symbols directly intead of strings.
283 /// **Known problems:** None.
288 /// symbol.as_str() == "clippy";
293 /// symbol == sym::clippy;
295 pub UNNECESSARY_SYMBOL_STR,
297 "unnecessary conversion between Symbol and string"
300 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
302 impl EarlyLintPass for ClippyLintsInternal {
303 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
304 if let Some(utils) = krate
308 .find(|item| item.ident.name.as_str() == "utils")
310 if let ItemKind::Mod(ref utils_mod) = utils.kind {
311 if let Some(paths) = utils_mod.items.iter().find(|item| item.ident.name.as_str() == "paths") {
312 if let ItemKind::Mod(ref paths_mod) = paths.kind {
313 let mut last_name: Option<SymbolStr> = None;
314 for item in &*paths_mod.items {
315 let name = item.ident.as_str();
316 if let Some(ref last_name) = last_name {
317 if **last_name > *name {
320 CLIPPY_LINTS_INTERNAL,
322 "this constant should be before the previous constant due to lexical \
327 last_name = Some(name);
336 #[derive(Clone, Debug, Default)]
337 pub struct LintWithoutLintPass {
338 declared_lints: FxHashMap<Symbol, Span>,
339 registered_lints: FxHashSet<Symbol>,
342 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
344 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
345 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
346 if !run_lints(cx, &[DEFAULT_LINT], item.hir_id) {
350 if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
351 if is_lint_ref_type(cx, ty) {
352 let expr = &cx.tcx.hir().body(body_id).value;
354 if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
355 if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
358 .find(|f| f.ident.as_str() == "desc")
359 .expect("lints must have a description field");
360 if let ExprKind::Lit(Spanned {
361 node: LitKind::Str(ref sym, _),
363 }) = field.expr.kind;
364 if sym.as_str() == "default lint description";
371 &format!("the lint `{}` has the default lint description", item.ident.name),
375 self.declared_lints.insert(item.ident.name, item.span);
377 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
378 || is_expn_of(item.span, "declare_lint_pass").is_some()
380 if let hir::ItemKind::Impl(hir::Impl {
382 items: ref impl_item_refs,
386 let mut collector = LintCollector {
387 output: &mut self.registered_lints,
390 let body_id = cx.tcx.hir().body_owned_by(
393 .find(|iiref| iiref.ident.as_str() == "get_lints")
394 .expect("LintPass needs to implement get_lints")
398 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
403 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
404 if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
408 for (lint_name, &lint_span) in &self.declared_lints {
409 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
410 // file points to "<rustc macros>".
411 // `compiletest-rs` thinks that's an error in a different file and
412 // just ignores it. This causes the test in compile-fail/lint_pass
413 // not able to capture the error.
414 // Therefore, we need to climb the macro expansion tree and find the
415 // actual span that invoked `declare_tool_lint!`:
416 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
418 if !self.registered_lints.contains(lint_name) {
421 LINT_WITHOUT_LINT_PASS,
423 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
430 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
435 mutbl: Mutability::Not,
439 if let TyKind::Path(ref path) = inner.kind {
440 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
441 return match_def_path(cx, def_id, &paths::LINT);
449 struct LintCollector<'a, 'tcx> {
450 output: &'a mut FxHashSet<Symbol>,
451 cx: &'a LateContext<'tcx>,
454 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
455 type Map = Map<'tcx>;
457 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
458 if path.segments.len() == 1 {
459 self.output.insert(path.segments[0].ident.name);
463 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
464 NestedVisitorMap::All(self.cx.tcx.hir())
468 #[derive(Clone, Default)]
469 pub struct CompilerLintFunctions {
470 map: FxHashMap<&'static str, &'static str>,
473 impl CompilerLintFunctions {
475 pub fn new() -> Self {
476 let mut map = FxHashMap::default();
477 map.insert("span_lint", "utils::span_lint");
478 map.insert("struct_span_lint", "utils::span_lint");
479 map.insert("lint", "utils::span_lint");
480 map.insert("span_lint_note", "utils::span_lint_and_note");
481 map.insert("span_lint_help", "utils::span_lint_and_help");
486 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
488 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
489 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
490 if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
495 if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
496 let fn_name = path.ident;
497 if let Some(sugg) = self.map.get(&*fn_name.as_str());
498 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
499 if match_type(cx, ty, &paths::EARLY_CONTEXT)
500 || match_type(cx, ty, &paths::LATE_CONTEXT);
504 COMPILER_LINT_FUNCTIONS,
506 "usage of a compiler lint function",
508 &format!("please use the Clippy variant of this function: `{}`", sugg),
515 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
517 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
518 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
519 if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
523 let (method_names, arg_lists, spans) = method_calls(expr, 2);
524 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
525 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
527 if let ["expn_data", "outer_expn"] = method_names.as_slice();
528 let args = arg_lists[1];
530 let self_arg = &args[0];
531 let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
532 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
536 OUTER_EXPN_EXPN_DATA,
537 spans[1].with_hi(expr.span.hi()),
538 "usage of `outer_expn().expn_data()`",
540 "outer_expn_data()".to_string(),
541 Applicability::MachineApplicable,
548 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
550 impl EarlyLintPass for ProduceIce {
551 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
552 if is_trigger_fn(fn_kind) {
553 panic!("Would you like some help with that?");
558 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
560 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
561 FnKind::Closure(..) => false,
565 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
567 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
568 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
569 if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
574 if let ExprKind::Call(ref func, ref and_then_args) = expr.kind;
575 if let ExprKind::Path(ref path) = func.kind;
576 if match_qpath(path, &["span_lint_and_then"]);
577 if and_then_args.len() == 5;
578 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
579 let body = cx.tcx.hir().body(*body_id);
580 if let ExprKind::Block(block, _) = &body.value.kind;
581 let stmts = &block.stmts;
582 if stmts.len() == 1 && block.expr.is_none();
583 if let StmtKind::Semi(only_expr) = &stmts[0].kind;
584 if let ExprKind::MethodCall(ref ps, _, ref span_call_args, _) = &only_expr.kind;
585 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
586 let mut sle = SpanlessEq::new(cx).deny_side_effects();
588 match &*ps.ident.as_str() {
589 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
590 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
592 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
593 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
594 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
596 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
597 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
598 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
601 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
602 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
605 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
606 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
615 struct AndThenSnippets<'a> {
622 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
623 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
624 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
625 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
626 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
636 struct SpanSuggestionSnippets<'a> {
639 applicability: Cow<'a, str>,
642 fn span_suggestion_snippets<'a, 'hir>(
643 cx: &LateContext<'_>,
644 span_call_args: &'hir [Expr<'hir>],
645 ) -> SpanSuggestionSnippets<'a> {
646 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
647 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
648 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
650 SpanSuggestionSnippets {
653 applicability: applicability_snippet,
657 fn suggest_suggestion(
658 cx: &LateContext<'_>,
660 and_then_snippets: &AndThenSnippets<'_>,
661 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
665 COLLAPSIBLE_SPAN_LINT_CALLS,
667 "this call is collapsible",
670 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
671 and_then_snippets.cx,
672 and_then_snippets.lint,
673 and_then_snippets.span,
674 and_then_snippets.msg,
675 span_suggestion_snippets.help,
676 span_suggestion_snippets.sugg,
677 span_suggestion_snippets.applicability
679 Applicability::MachineApplicable,
684 cx: &LateContext<'_>,
686 and_then_snippets: &AndThenSnippets<'_>,
690 let option_span = if with_span {
691 format!("Some({})", and_then_snippets.span)
698 COLLAPSIBLE_SPAN_LINT_CALLS,
700 "this call is collapsible",
703 "span_lint_and_help({}, {}, {}, {}, {}, {})",
704 and_then_snippets.cx,
705 and_then_snippets.lint,
706 and_then_snippets.span,
707 and_then_snippets.msg,
711 Applicability::MachineApplicable,
716 cx: &LateContext<'_>,
718 and_then_snippets: &AndThenSnippets<'_>,
722 let note_span = if with_span {
723 format!("Some({})", and_then_snippets.span)
730 COLLAPSIBLE_SPAN_LINT_CALLS,
732 "this call is collspible",
735 "span_lint_and_note({}, {}, {}, {}, {}, {})",
736 and_then_snippets.cx,
737 and_then_snippets.lint,
738 and_then_snippets.span,
739 and_then_snippets.msg,
743 Applicability::MachineApplicable,
747 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
749 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
750 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
751 if !run_lints(cx, &[MATCH_TYPE_ON_DIAGNOSTIC_ITEM], expr.hir_id) {
756 // Check if this is a call to utils::match_type()
757 if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
758 if let ExprKind::Path(fn_qpath) = &fn_path.kind;
759 if match_qpath(&fn_qpath, &["utils", "match_type"]);
760 // Extract the path to the matched type
761 if let Some(segments) = path_to_matched_type(cx, ty_path);
762 let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
763 if let Some(ty_did) = path_to_res(cx, &segments[..]).and_then(|res| res.opt_def_id());
764 // Check if the matched type is a diagnostic item
765 let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
766 if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
768 let cx_snippet = snippet(cx, context.span, "_");
769 let ty_snippet = snippet(cx, ty.span, "_");
773 MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
775 "usage of `utils::match_type()` on a type diagnostic item",
777 format!("utils::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
778 Applicability::MaybeIncorrect,
785 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
786 use rustc_hir::ItemKind;
789 ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
790 ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
791 Res::Local(hir_id) => {
792 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
793 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
794 if let Some(init) = local.init {
795 return path_to_matched_type(cx, init);
799 Res::Def(DefKind::Const | DefKind::Static, def_id) => {
800 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
801 if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
802 let body = cx.tcx.hir().body(body_id);
803 return path_to_matched_type(cx, &body.value);
809 ExprKind::Array(exprs) => {
810 let segments: Vec<SymbolStr> = exprs
813 if let ExprKind::Lit(lit) = &expr.kind {
814 if let LitKind::Str(sym, _) = lit.node {
815 return Some(sym.as_str());
823 if segments.len() == exprs.len() {
824 return Some(segments);
833 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
834 // module. That's all it does and all it needs to do.
835 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
836 if path_to_res(cx, path).is_some() {
840 // Some implementations can't be found by `path_to_res`, particularly inherent
841 // implementations of native types. Check lang items.
842 let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
843 let lang_items = cx.tcx.lang_items();
844 for lang_item in lang_items.items() {
845 if let Some(def_id) = lang_item {
846 let lang_item_path = cx.get_def_path(*def_id);
847 if path_syms.starts_with(&lang_item_path) {
848 if let [item] = &path_syms[lang_item_path.len()..] {
849 for child in cx.tcx.item_children(*def_id) {
850 if child.ident.name == *item {
862 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
864 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
865 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
866 let local_def_id = &cx.tcx.parent_module(item.hir_id);
867 let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
869 if mod_name.as_str() == "paths";
870 if let hir::ItemKind::Const(ty, body_id) = item.kind;
871 let ty = hir_ty_to_ty(cx.tcx, ty);
872 if let ty::Array(el_ty, _) = &ty.kind();
873 if let ty::Ref(_, el_ty, _) = &el_ty.kind();
875 let body = cx.tcx.hir().body(body_id);
876 let typeck_results = cx.tcx.typeck_body(body_id);
877 if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
878 let path: Vec<&str> = path.iter().map(|x| {
879 if let Constant::Str(s) = x {
882 // We checked the type of the constant above
886 if !check_path(cx, &path[..]);
888 span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
895 pub struct InterningDefinedSymbol {
896 // Maps the symbol value to the constant DefId.
897 symbol_map: FxHashMap<u32, DefId>,
900 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
902 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
903 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
904 if !self.symbol_map.is_empty() {
908 for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
909 if let Some(Res::Def(_, def_id)) = path_to_res(cx, module) {
910 for item in cx.tcx.item_children(def_id).iter() {
912 if let Res::Def(DefKind::Const, item_def_id) = item.res;
913 let ty = cx.tcx.type_of(item_def_id);
914 if match_type(cx, ty, &paths::SYMBOL);
915 if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
916 if let Ok(value) = value.to_u32();
918 self.symbol_map.insert(value, item_def_id);
926 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
928 if let ExprKind::Call(func, [arg]) = &expr.kind;
929 if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
930 if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
931 if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
932 let value = Symbol::intern(&arg).as_u32();
933 if let Some(&def_id) = self.symbol_map.get(&value);
937 INTERNING_DEFINED_SYMBOL,
938 is_expn_of(expr.span, "sym").unwrap_or(expr.span),
939 "interning a defined symbol",
941 cx.tcx.def_path_str(def_id),
942 Applicability::MachineApplicable,
946 if let ExprKind::Binary(op, left, right) = expr.kind {
947 if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
949 (left, self.symbol_str_expr(left, cx)),
950 (right, self.symbol_str_expr(right, cx)),
953 // both operands are a symbol string
954 [(_, Some(left)), (_, Some(right))] => {
957 UNNECESSARY_SYMBOL_STR,
959 "unnecessary `Symbol` to string conversion",
963 left.as_symbol_snippet(cx),
965 right.as_symbol_snippet(cx),
967 Applicability::MachineApplicable,
970 // one of the operands is a symbol string
971 [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
972 // creating an owned string for comparison
973 if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
976 UNNECESSARY_SYMBOL_STR,
978 "unnecessary string allocation",
980 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
981 Applicability::MachineApplicable,
986 [(_, None), (_, None)] => {},
993 impl InterningDefinedSymbol {
994 fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
995 static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
996 static SYMBOL_STR_PATHS: &[&[&str]] = &[
997 &paths::SYMBOL_AS_STR,
998 &paths::SYMBOL_TO_IDENT_STRING,
999 &paths::TO_STRING_METHOD,
1001 // SymbolStr might be de-referenced: `&*symbol.as_str()`
1002 let call = if_chain! {
1003 if let ExprKind::AddrOf(_, _, e) = expr.kind;
1004 if let ExprKind::Unary(UnOp::UnDeref, e) = e.kind;
1005 then { e } else { expr }
1009 if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1010 if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1011 let ty = cx.typeck_results().expr_ty(item);
1012 // ...on either an Ident or a Symbol
1013 if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1015 } else if match_type(cx, ty, &paths::IDENT) {
1020 // ...which converts it to a string
1021 let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1022 if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1024 let is_to_owned = path.last().unwrap().ends_with("string");
1025 return Some(SymbolStrExpr::Expr {
1032 // is a string constant
1033 if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1034 let value = Symbol::intern(&s).as_u32();
1035 // ...which matches a symbol constant
1036 if let Some(&def_id) = self.symbol_map.get(&value) {
1037 return Some(SymbolStrExpr::Const(def_id));
1044 enum SymbolStrExpr<'tcx> {
1045 /// a string constant with a corresponding symbol constant
1047 /// a "symbol to string" expression like `symbol.as_str()`
1049 /// part that evaluates to `Symbol` or `Ident`
1050 item: &'tcx Expr<'tcx>,
1052 /// whether an owned `String` is created like `to_ident_string()`
1057 impl<'tcx> SymbolStrExpr<'tcx> {
1058 /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1059 fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1061 Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1062 Self::Expr { item, is_ident, .. } => {
1063 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1066 snip.to_mut().push_str(".name");