StringFindStartswithCheck.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. //===--- StringFindStartswithCheck.cc - clang-tidy---------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "StringFindStartswithCheck.h"
  9. #include "../utils/OptionsUtils.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/ASTMatchers/ASTMatchers.h"
  12. #include "clang/Frontend/CompilerInstance.h"
  13. #include "clang/Lex/Lexer.h"
  14. #include "clang/Lex/Preprocessor.h"
  15. using namespace clang::ast_matchers;
  16. namespace clang::tidy::abseil {
  17. StringFindStartswithCheck::StringFindStartswithCheck(StringRef Name,
  18. ClangTidyContext *Context)
  19. : ClangTidyCheck(Name, Context),
  20. StringLikeClasses(utils::options::parseStringList(
  21. Options.get("StringLikeClasses", "::std::basic_string"))),
  22. IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
  23. utils::IncludeSorter::IS_LLVM),
  24. areDiagsSelfContained()),
  25. AbseilStringsMatchHeader(
  26. Options.get("AbseilStringsMatchHeader", "absl/strings/match.h")) {}
  27. void StringFindStartswithCheck::registerMatchers(MatchFinder *Finder) {
  28. auto ZeroLiteral = integerLiteral(equals(0));
  29. auto StringClassMatcher = cxxRecordDecl(hasAnyName(StringLikeClasses));
  30. auto StringType = hasUnqualifiedDesugaredType(
  31. recordType(hasDeclaration(StringClassMatcher)));
  32. auto StringFind = cxxMemberCallExpr(
  33. // .find()-call on a string...
  34. callee(cxxMethodDecl(hasName("find")).bind("findfun")),
  35. on(hasType(StringType)),
  36. // ... with some search expression ...
  37. hasArgument(0, expr().bind("needle")),
  38. // ... and either "0" as second argument or the default argument (also 0).
  39. anyOf(hasArgument(1, ZeroLiteral), hasArgument(1, cxxDefaultArgExpr())));
  40. Finder->addMatcher(
  41. // Match [=!]= with a zero on one side and a string.find on the other.
  42. binaryOperator(
  43. hasAnyOperatorName("==", "!="),
  44. hasOperands(ignoringParenImpCasts(ZeroLiteral),
  45. ignoringParenImpCasts(StringFind.bind("findexpr"))))
  46. .bind("expr"),
  47. this);
  48. auto StringRFind = cxxMemberCallExpr(
  49. // .rfind()-call on a string...
  50. callee(cxxMethodDecl(hasName("rfind")).bind("findfun")),
  51. on(hasType(StringType)),
  52. // ... with some search expression ...
  53. hasArgument(0, expr().bind("needle")),
  54. // ... and "0" as second argument.
  55. hasArgument(1, ZeroLiteral));
  56. Finder->addMatcher(
  57. // Match [=!]= with either a zero or npos on one side and a string.rfind
  58. // on the other.
  59. binaryOperator(
  60. hasAnyOperatorName("==", "!="),
  61. hasOperands(ignoringParenImpCasts(ZeroLiteral),
  62. ignoringParenImpCasts(StringRFind.bind("findexpr"))))
  63. .bind("expr"),
  64. this);
  65. }
  66. void StringFindStartswithCheck::check(const MatchFinder::MatchResult &Result) {
  67. const ASTContext &Context = *Result.Context;
  68. const SourceManager &Source = Context.getSourceManager();
  69. // Extract matching (sub)expressions
  70. const auto *ComparisonExpr = Result.Nodes.getNodeAs<BinaryOperator>("expr");
  71. assert(ComparisonExpr != nullptr);
  72. const auto *Needle = Result.Nodes.getNodeAs<Expr>("needle");
  73. assert(Needle != nullptr);
  74. const Expr *Haystack = Result.Nodes.getNodeAs<CXXMemberCallExpr>("findexpr")
  75. ->getImplicitObjectArgument();
  76. assert(Haystack != nullptr);
  77. const CXXMethodDecl *FindFun =
  78. Result.Nodes.getNodeAs<CXXMethodDecl>("findfun");
  79. assert(FindFun != nullptr);
  80. bool Rev = FindFun->getName().contains("rfind");
  81. if (ComparisonExpr->getBeginLoc().isMacroID())
  82. return;
  83. // Get the source code blocks (as characters) for both the string object
  84. // and the search expression
  85. const StringRef NeedleExprCode = Lexer::getSourceText(
  86. CharSourceRange::getTokenRange(Needle->getSourceRange()), Source,
  87. Context.getLangOpts());
  88. const StringRef HaystackExprCode = Lexer::getSourceText(
  89. CharSourceRange::getTokenRange(Haystack->getSourceRange()), Source,
  90. Context.getLangOpts());
  91. // Create the StartsWith string, negating if comparison was "!=".
  92. bool Neg = ComparisonExpr->getOpcode() == BO_NE;
  93. // Create the warning message and a FixIt hint replacing the original expr.
  94. auto Diagnostic =
  95. diag(ComparisonExpr->getBeginLoc(),
  96. "use %select{absl::StartsWith|!absl::StartsWith}0 "
  97. "instead of %select{find()|rfind()}1 %select{==|!=}0 0")
  98. << Neg << Rev;
  99. Diagnostic << FixItHint::CreateReplacement(
  100. ComparisonExpr->getSourceRange(),
  101. ((Neg ? "!absl::StartsWith(" : "absl::StartsWith(") + HaystackExprCode +
  102. ", " + NeedleExprCode + ")")
  103. .str());
  104. // Create a preprocessor #include FixIt hint (createIncludeInsertion checks
  105. // whether this already exists).
  106. Diagnostic << IncludeInserter.createIncludeInsertion(
  107. Source.getFileID(ComparisonExpr->getBeginLoc()),
  108. AbseilStringsMatchHeader);
  109. }
  110. void StringFindStartswithCheck::registerPPCallbacks(
  111. const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
  112. IncludeInserter.registerPreprocessor(PP);
  113. }
  114. void StringFindStartswithCheck::storeOptions(
  115. ClangTidyOptions::OptionMap &Opts) {
  116. Options.store(Opts, "StringLikeClasses",
  117. utils::options::serializeStringList(StringLikeClasses));
  118. Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
  119. Options.store(Opts, "AbseilStringsMatchHeader", AbseilStringsMatchHeader);
  120. }
  121. } // namespace clang::tidy::abseil