1 use crate::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg};
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::match_type;
5 use clippy_utils::{is_expn_of, match_def_path, match_qpath, method_calls, path_to_res, paths, run_lints, SpanlessEq};
6 use if_chain::if_chain;
7 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, ModKind, 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.items.iter().find(|item| item.ident.name.as_str() == "utils") {
305 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
306 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
307 if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
308 let mut last_name: Option<SymbolStr> = None;
310 let name = item.ident.as_str();
311 if let Some(ref last_name) = last_name {
312 if **last_name > *name {
315 CLIPPY_LINTS_INTERNAL,
317 "this constant should be before the previous constant due to lexical \
322 last_name = Some(name);
331 #[derive(Clone, Debug, Default)]
332 pub struct LintWithoutLintPass {
333 declared_lints: FxHashMap<Symbol, Span>,
334 registered_lints: FxHashSet<Symbol>,
337 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
339 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
340 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
341 if !run_lints(cx, &[DEFAULT_LINT], item.hir_id()) {
345 if let hir::ItemKind::Static(ref ty, Mutability::Not, body_id) = item.kind {
346 if is_lint_ref_type(cx, ty) {
347 let expr = &cx.tcx.hir().body(body_id).value;
349 if let ExprKind::AddrOf(_, _, ref inner_exp) = expr.kind;
350 if let ExprKind::Struct(_, ref fields, _) = inner_exp.kind;
353 .find(|f| f.ident.as_str() == "desc")
354 .expect("lints must have a description field");
355 if let ExprKind::Lit(Spanned {
356 node: LitKind::Str(ref sym, _),
358 }) = field.expr.kind;
359 if sym.as_str() == "default lint description";
366 &format!("the lint `{}` has the default lint description", item.ident.name),
370 self.declared_lints.insert(item.ident.name, item.span);
372 } else if is_expn_of(item.span, "impl_lint_pass").is_some()
373 || is_expn_of(item.span, "declare_lint_pass").is_some()
375 if let hir::ItemKind::Impl(hir::Impl {
377 items: ref impl_item_refs,
381 let mut collector = LintCollector {
382 output: &mut self.registered_lints,
385 let body_id = cx.tcx.hir().body_owned_by(
388 .find(|iiref| iiref.ident.as_str() == "get_lints")
389 .expect("LintPass needs to implement get_lints")
393 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
398 fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
399 if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
403 for (lint_name, &lint_span) in &self.declared_lints {
404 // When using the `declare_tool_lint!` macro, the original `lint_span`'s
405 // file points to "<rustc macros>".
406 // `compiletest-rs` thinks that's an error in a different file and
407 // just ignores it. This causes the test in compile-fail/lint_pass
408 // not able to capture the error.
409 // Therefore, we need to climb the macro expansion tree and find the
410 // actual span that invoked `declare_tool_lint!`:
411 let lint_span = lint_span.ctxt().outer_expn_data().call_site;
413 if !self.registered_lints.contains(lint_name) {
416 LINT_WITHOUT_LINT_PASS,
418 &format!("the lint `{}` is not added to any `LintPass`", lint_name),
425 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
430 mutbl: Mutability::Not,
434 if let TyKind::Path(ref path) = inner.kind {
435 if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
436 return match_def_path(cx, def_id, &paths::LINT);
444 struct LintCollector<'a, 'tcx> {
445 output: &'a mut FxHashSet<Symbol>,
446 cx: &'a LateContext<'tcx>,
449 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
450 type Map = Map<'tcx>;
452 fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
453 if path.segments.len() == 1 {
454 self.output.insert(path.segments[0].ident.name);
458 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
459 NestedVisitorMap::All(self.cx.tcx.hir())
463 #[derive(Clone, Default)]
464 pub struct CompilerLintFunctions {
465 map: FxHashMap<&'static str, &'static str>,
468 impl CompilerLintFunctions {
470 pub fn new() -> Self {
471 let mut map = FxHashMap::default();
472 map.insert("span_lint", "utils::span_lint");
473 map.insert("struct_span_lint", "utils::span_lint");
474 map.insert("lint", "utils::span_lint");
475 map.insert("span_lint_note", "utils::span_lint_and_note");
476 map.insert("span_lint_help", "utils::span_lint_and_help");
481 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
483 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
484 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
485 if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
490 if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
491 let fn_name = path.ident;
492 if let Some(sugg) = self.map.get(&*fn_name.as_str());
493 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
494 if match_type(cx, ty, &paths::EARLY_CONTEXT)
495 || match_type(cx, ty, &paths::LATE_CONTEXT);
499 COMPILER_LINT_FUNCTIONS,
501 "usage of a compiler lint function",
503 &format!("please use the Clippy variant of this function: `{}`", sugg),
510 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
512 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
513 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
514 if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
518 let (method_names, arg_lists, spans) = method_calls(expr, 2);
519 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
520 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
522 if let ["expn_data", "outer_expn"] = method_names.as_slice();
523 let args = arg_lists[1];
525 let self_arg = &args[0];
526 let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
527 if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
531 OUTER_EXPN_EXPN_DATA,
532 spans[1].with_hi(expr.span.hi()),
533 "usage of `outer_expn().expn_data()`",
535 "outer_expn_data()".to_string(),
536 Applicability::MachineApplicable,
543 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
545 impl EarlyLintPass for ProduceIce {
546 fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
547 if is_trigger_fn(fn_kind) {
548 panic!("Would you like some help with that?");
553 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
555 FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
556 FnKind::Closure(..) => false,
560 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
562 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
563 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
564 if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
569 if let ExprKind::Call(ref func, ref and_then_args) = expr.kind;
570 if let ExprKind::Path(ref path) = func.kind;
571 if match_qpath(path, &["span_lint_and_then"]);
572 if and_then_args.len() == 5;
573 if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
574 let body = cx.tcx.hir().body(*body_id);
575 if let ExprKind::Block(block, _) = &body.value.kind;
576 let stmts = &block.stmts;
577 if stmts.len() == 1 && block.expr.is_none();
578 if let StmtKind::Semi(only_expr) = &stmts[0].kind;
579 if let ExprKind::MethodCall(ref ps, _, ref span_call_args, _) = &only_expr.kind;
580 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
581 let mut sle = SpanlessEq::new(cx).deny_side_effects();
583 match &*ps.ident.as_str() {
584 "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
585 suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
587 "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
588 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
589 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
591 "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
592 let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
593 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
596 let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
597 suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
600 let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
601 suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
610 struct AndThenSnippets<'a> {
617 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
618 let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
619 let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
620 let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
621 let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
631 struct SpanSuggestionSnippets<'a> {
634 applicability: Cow<'a, str>,
637 fn span_suggestion_snippets<'a, 'hir>(
638 cx: &LateContext<'_>,
639 span_call_args: &'hir [Expr<'hir>],
640 ) -> SpanSuggestionSnippets<'a> {
641 let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
642 let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
643 let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
645 SpanSuggestionSnippets {
648 applicability: applicability_snippet,
652 fn suggest_suggestion(
653 cx: &LateContext<'_>,
655 and_then_snippets: &AndThenSnippets<'_>,
656 span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
660 COLLAPSIBLE_SPAN_LINT_CALLS,
662 "this call is collapsible",
665 "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
666 and_then_snippets.cx,
667 and_then_snippets.lint,
668 and_then_snippets.span,
669 and_then_snippets.msg,
670 span_suggestion_snippets.help,
671 span_suggestion_snippets.sugg,
672 span_suggestion_snippets.applicability
674 Applicability::MachineApplicable,
679 cx: &LateContext<'_>,
681 and_then_snippets: &AndThenSnippets<'_>,
685 let option_span = if with_span {
686 format!("Some({})", and_then_snippets.span)
693 COLLAPSIBLE_SPAN_LINT_CALLS,
695 "this call is collapsible",
698 "span_lint_and_help({}, {}, {}, {}, {}, {})",
699 and_then_snippets.cx,
700 and_then_snippets.lint,
701 and_then_snippets.span,
702 and_then_snippets.msg,
706 Applicability::MachineApplicable,
711 cx: &LateContext<'_>,
713 and_then_snippets: &AndThenSnippets<'_>,
717 let note_span = if with_span {
718 format!("Some({})", and_then_snippets.span)
725 COLLAPSIBLE_SPAN_LINT_CALLS,
727 "this call is collspible",
730 "span_lint_and_note({}, {}, {}, {}, {}, {})",
731 and_then_snippets.cx,
732 and_then_snippets.lint,
733 and_then_snippets.span,
734 and_then_snippets.msg,
738 Applicability::MachineApplicable,
742 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
744 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
745 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
746 if !run_lints(cx, &[MATCH_TYPE_ON_DIAGNOSTIC_ITEM], expr.hir_id) {
751 // Check if this is a call to utils::match_type()
752 if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
753 if let ExprKind::Path(fn_qpath) = &fn_path.kind;
754 if match_qpath(&fn_qpath, &["utils", "match_type"]);
755 // Extract the path to the matched type
756 if let Some(segments) = path_to_matched_type(cx, ty_path);
757 let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
758 if let Some(ty_did) = path_to_res(cx, &segments[..]).opt_def_id();
759 // Check if the matched type is a diagnostic item
760 let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
761 if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
763 let cx_snippet = snippet(cx, context.span, "_");
764 let ty_snippet = snippet(cx, ty.span, "_");
768 MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
770 "usage of `utils::match_type()` on a type diagnostic item",
772 format!("utils::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
773 Applicability::MaybeIncorrect,
780 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
781 use rustc_hir::ItemKind;
784 ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
785 ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
786 Res::Local(hir_id) => {
787 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
788 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
789 if let Some(init) = local.init {
790 return path_to_matched_type(cx, init);
794 Res::Def(DefKind::Const | DefKind::Static, def_id) => {
795 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
796 if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
797 let body = cx.tcx.hir().body(body_id);
798 return path_to_matched_type(cx, &body.value);
804 ExprKind::Array(exprs) => {
805 let segments: Vec<SymbolStr> = exprs
808 if let ExprKind::Lit(lit) = &expr.kind {
809 if let LitKind::Str(sym, _) = lit.node {
810 return Some(sym.as_str());
818 if segments.len() == exprs.len() {
819 return Some(segments);
828 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
829 // module. That's all it does and all it needs to do.
830 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
831 if path_to_res(cx, path) != Res::Err {
835 // Some implementations can't be found by `path_to_res`, particularly inherent
836 // implementations of native types. Check lang items.
837 let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
838 let lang_items = cx.tcx.lang_items();
839 for item_def_id in lang_items.items().iter().flatten() {
840 let lang_item_path = cx.get_def_path(*item_def_id);
841 if path_syms.starts_with(&lang_item_path) {
842 if let [item] = &path_syms[lang_item_path.len()..] {
843 for child in cx.tcx.item_children(*item_def_id) {
844 if child.ident.name == *item {
855 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
857 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
858 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
859 let local_def_id = &cx.tcx.parent_module(item.hir_id());
860 let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
862 if mod_name.as_str() == "paths";
863 if let hir::ItemKind::Const(ty, body_id) = item.kind;
864 let ty = hir_ty_to_ty(cx.tcx, ty);
865 if let ty::Array(el_ty, _) = &ty.kind();
866 if let ty::Ref(_, el_ty, _) = &el_ty.kind();
868 let body = cx.tcx.hir().body(body_id);
869 let typeck_results = cx.tcx.typeck_body(body_id);
870 if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
871 let path: Vec<&str> = path.iter().map(|x| {
872 if let Constant::Str(s) = x {
875 // We checked the type of the constant above
879 if !check_path(cx, &path[..]);
881 span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
888 pub struct InterningDefinedSymbol {
889 // Maps the symbol value to the constant DefId.
890 symbol_map: FxHashMap<u32, DefId>,
893 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
895 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
896 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
897 if !self.symbol_map.is_empty() {
901 for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
902 if let Some(def_id) = path_to_res(cx, module).opt_def_id() {
903 for item in cx.tcx.item_children(def_id).iter() {
905 if let Res::Def(DefKind::Const, item_def_id) = item.res;
906 let ty = cx.tcx.type_of(item_def_id);
907 if match_type(cx, ty, &paths::SYMBOL);
908 if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
909 if let Ok(value) = value.to_u32();
911 self.symbol_map.insert(value, item_def_id);
919 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
921 if let ExprKind::Call(func, [arg]) = &expr.kind;
922 if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
923 if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
924 if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
925 let value = Symbol::intern(&arg).as_u32();
926 if let Some(&def_id) = self.symbol_map.get(&value);
930 INTERNING_DEFINED_SYMBOL,
931 is_expn_of(expr.span, "sym").unwrap_or(expr.span),
932 "interning a defined symbol",
934 cx.tcx.def_path_str(def_id),
935 Applicability::MachineApplicable,
939 if let ExprKind::Binary(op, left, right) = expr.kind {
940 if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
942 (left, self.symbol_str_expr(left, cx)),
943 (right, self.symbol_str_expr(right, cx)),
946 // both operands are a symbol string
947 [(_, Some(left)), (_, Some(right))] => {
950 UNNECESSARY_SYMBOL_STR,
952 "unnecessary `Symbol` to string conversion",
956 left.as_symbol_snippet(cx),
958 right.as_symbol_snippet(cx),
960 Applicability::MachineApplicable,
963 // one of the operands is a symbol string
964 [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
965 // creating an owned string for comparison
966 if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
969 UNNECESSARY_SYMBOL_STR,
971 "unnecessary string allocation",
973 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
974 Applicability::MachineApplicable,
979 [(_, None), (_, None)] => {},
986 impl InterningDefinedSymbol {
987 fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
988 static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
989 static SYMBOL_STR_PATHS: &[&[&str]] = &[
990 &paths::SYMBOL_AS_STR,
991 &paths::SYMBOL_TO_IDENT_STRING,
992 &paths::TO_STRING_METHOD,
994 // SymbolStr might be de-referenced: `&*symbol.as_str()`
995 let call = if_chain! {
996 if let ExprKind::AddrOf(_, _, e) = expr.kind;
997 if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
998 then { e } else { expr }
1002 if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1003 if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1004 let ty = cx.typeck_results().expr_ty(item);
1005 // ...on either an Ident or a Symbol
1006 if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1008 } else if match_type(cx, ty, &paths::IDENT) {
1013 // ...which converts it to a string
1014 let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1015 if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1017 let is_to_owned = path.last().unwrap().ends_with("string");
1018 return Some(SymbolStrExpr::Expr {
1025 // is a string constant
1026 if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1027 let value = Symbol::intern(&s).as_u32();
1028 // ...which matches a symbol constant
1029 if let Some(&def_id) = self.symbol_map.get(&value) {
1030 return Some(SymbolStrExpr::Const(def_id));
1037 enum SymbolStrExpr<'tcx> {
1038 /// a string constant with a corresponding symbol constant
1040 /// a "symbol to string" expression like `symbol.as_str()`
1042 /// part that evaluates to `Symbol` or `Ident`
1043 item: &'tcx Expr<'tcx>,
1045 /// whether an owned `String` is created like `to_ident_string()`
1050 impl<'tcx> SymbolStrExpr<'tcx> {
1051 /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1052 fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1054 Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1055 Self::Expr { item, is_ident, .. } => {
1056 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1059 snip.to_mut().push_str(".name");