|
| 1 | +use clippy_utils::consts::{ConstEvalCtxt, Constant}; |
| 2 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 3 | +use clippy_utils::source::snippet_with_applicability; |
| 4 | +use clippy_utils::ty::match_type; |
| 5 | +use clippy_utils::{match_function_call, paths}; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::{BinOpKind, Expr, ExprKind}; |
| 8 | +use rustc_lint::{LateContext, LateLintPass}; |
| 9 | +use rustc_session::declare_lint_pass; |
| 10 | + |
| 11 | +declare_clippy_lint! { |
| 12 | + /// ### What it does |
| 13 | + /// |
| 14 | + /// Detects symbol comparision using `Symbol::intern`. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// |
| 18 | + /// Comparision via `Symbol::as_str()` is faster if the interned symbols are not reused. |
| 19 | + /// |
| 20 | + /// ### Example |
| 21 | + /// |
| 22 | + /// None, see suggestion. |
| 23 | + pub SLOW_SYMBOL_COMPARISONS, |
| 24 | + internal, |
| 25 | + "detects slow comparisions of symbol" |
| 26 | +} |
| 27 | + |
| 28 | +declare_lint_pass!(SlowSymbolComparisons => [SLOW_SYMBOL_COMPARISONS]); |
| 29 | + |
| 30 | +impl<'tcx> LateLintPass<'tcx> for SlowSymbolComparisons { |
| 31 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &Expr<'tcx>) { |
| 32 | + if let ExprKind::Binary(op, left, right) = expr.kind |
| 33 | + && op.node == BinOpKind::Eq |
| 34 | + && match_type(cx, cx.typeck_results().expr_ty(left), &paths::SYMBOL) |
| 35 | + && let Some([symbol_name_expr]) = match_function_call(cx, right, &paths::SYMBOL_INTERN) |
| 36 | + && let Some(Constant::Str(symbol_name)) = ConstEvalCtxt::new(cx).eval_simple(symbol_name_expr) |
| 37 | + { |
| 38 | + let mut applicability = Applicability::MachineApplicable; |
| 39 | + span_lint_and_sugg( |
| 40 | + cx, |
| 41 | + SLOW_SYMBOL_COMPARISONS, |
| 42 | + expr.span, |
| 43 | + "comparing `Symbol` via `Symbol::intern`", |
| 44 | + "use `Symbol::as_str` and check the string instead", |
| 45 | + format!( |
| 46 | + "{}.as_str() == \"{symbol_name}\"", |
| 47 | + snippet_with_applicability(cx, left.span, "symbol", &mut applicability) |
| 48 | + ), |
| 49 | + applicability, |
| 50 | + ); |
| 51 | + }; |
| 52 | + } |
| 53 | +} |
0 commit comments