1 use clippy_utils::diagnostics::span_lint_and_help;
2 use if_chain::if_chain;
3 use rustc_ast::ast::LitKind;
4 use rustc_hir::{Expr, ExprKind, PathSegment};
5 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::{source_map::Spanned, symbol::sym, Span};
10 declare_clippy_lint! {
12 /// Checks for calls to `ends_with` with possible file extensions
13 /// and suggests to use a case-insensitive approach instead.
15 /// ### Why is this bad?
16 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
20 /// fn is_rust_file(filename: &str) -> bool {
21 /// filename.ends_with(".rs")
26 /// fn is_rust_file(filename: &str) -> bool {
27 /// filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case("rs")) == Some(true)
30 #[clippy::version = "1.51.0"]
31 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
33 "Checks for calls to ends_with with case-sensitive file extensions"
36 declare_lint_pass!(CaseSensitiveFileExtensionComparisons => [CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS]);
38 fn check_case_sensitive_file_extension_comparison(ctx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Span> {
40 if let ExprKind::MethodCall(PathSegment { ident, .. }, [obj, extension, ..], span) = expr.kind;
41 if ident.as_str() == "ends_with";
42 if let ExprKind::Lit(Spanned { node: LitKind::Str(ext_literal, ..), ..}) = extension.kind;
43 if (2..=6).contains(&ext_literal.as_str().len());
44 if ext_literal.as_str().starts_with('.');
45 if ext_literal.as_str().chars().skip(1).all(|c| c.is_uppercase() || c.is_digit(10))
46 || ext_literal.as_str().chars().skip(1).all(|c| c.is_lowercase() || c.is_digit(10));
48 let mut ty = ctx.typeck_results().expr_ty(obj);
49 ty = match ty.kind() {
50 ty::Ref(_, ty, ..) => *ty,
58 ty::Adt(&ty::AdtDef { did, .. }, _) => {
59 if ctx.tcx.is_diagnostic_item(sym::String, did) {
70 impl<'tcx> LateLintPass<'tcx> for CaseSensitiveFileExtensionComparisons {
71 fn check_expr(&mut self, ctx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
72 if let Some(span) = check_case_sensitive_file_extension_comparison(ctx, expr) {
75 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
77 "case-sensitive file extension comparison",
79 "consider using a case-insensitive comparison instead",