1 use crate::utils::paths::STRING;
2 use crate::utils::{match_def_path, span_lint_and_help};
3 use if_chain::if_chain;
4 use lazy_static::lazy_static;
6 use rustc_ast::ast::LitKind;
7 use rustc_hir::{Expr, ExprKind, PathSegment};
8 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::{source_map::Spanned, Span};
13 declare_clippy_lint! {
15 /// Checks for calls to `ends_with` with possible file extensions
16 /// and suggests to use a case-insensitive approach instead.
18 /// **Why is this bad?**
19 /// `ends_with` is case-sensitive and may not detect files with a valid extension.
21 /// **Known problems:** None.
26 /// fn is_rust_file(filename: &str) -> bool {
27 /// filename.ends_with(".rs")
32 /// fn is_rust_file(filename: &str) -> bool {
33 /// filename.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case("rs")) == Some(true)
36 pub CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
38 "Checks for calls to ends_with with case-sensitive file extensions"
41 declare_lint_pass!(CaseSensitiveFileExtensionComparisons => [CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS]);
43 fn check_case_sensitive_file_extension_comparison(ctx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Span> {
45 static ref RE: Regex = Regex::new(r"^\.([a-z0-9]{1,5}|[A-Z0-9]{1,5})$").unwrap();
48 if let ExprKind::MethodCall(PathSegment { ident, .. }, _, [obj, extension, ..], span) = expr.kind;
49 if ident.as_str() == "ends_with";
50 if let ExprKind::Lit(Spanned { node: LitKind::Str(ext_literal, ..), ..}) = extension.kind;
51 if RE.is_match(&ext_literal.as_str());
53 let mut ty = ctx.typeck_results().expr_ty(obj);
54 ty = match ty.kind() {
55 ty::Ref(_, ty, ..) => ty,
63 ty::Adt(&ty::AdtDef { did, .. }, _) => {
64 if match_def_path(ctx, did, &STRING) {
75 impl LateLintPass<'tcx> for CaseSensitiveFileExtensionComparisons {
76 fn check_expr(&mut self, ctx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
77 if let Some(span) = check_case_sensitive_file_extension_comparison(ctx, expr) {
80 CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS,
82 "case-sensitive file extension comparison",
84 "consider using a case-insensitive comparison instead",