[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() [Cont.] (PR #95220)

Julian Schmidt via cfe-commits cfe-commits at lists.llvm.org
Sat Jun 15 06:14:10 PDT 2024


Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>,
Paul =?utf-8?q?Heidekrüger?= <paul.heidekrueger at tum.de>
Message-ID:
In-Reply-To: <llvm.org/llvm/llvm-project/pull/95220 at github.com>


================
@@ -0,0 +1,123 @@
+//===--- PreferAtOverSubscriptOperatorCheck.cpp - clang-tidy --------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "PreferAtOverSubscriptOperatorCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringRef.h"
+#include <algorithm>
+#include <numeric>
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::cppcoreguidelines {
+
+static constexpr std::array<llvm::StringRef, 3> DefaultExclusions = {
+    llvm::StringRef("std::map"), llvm::StringRef("std::unordered_map"),
+    llvm::StringRef("std::flat_map")};
+
+PreferAtOverSubscriptOperatorCheck::PreferAtOverSubscriptOperatorCheck(
+    StringRef Name, ClangTidyContext *Context)
+    : ClangTidyCheck(Name, Context) {
+
+  ExcludedClasses = clang::tidy::utils::options::parseStringList(
+      Options.get("ExcludeClasses", ""));
+  ExcludedClasses.insert(ExcludedClasses.end(), DefaultExclusions.begin(),
+                         DefaultExclusions.end());
+}
+
+void PreferAtOverSubscriptOperatorCheck::storeOptions(
+    ClangTidyOptions::OptionMap &Opts) {
+
+  if (ExcludedClasses.size() == DefaultExclusions.size()) {
+    Options.store(Opts, "ExcludeClasses", "");
+    return;
+  }
+
+  // Sum up the sizes of the defaults ( + semicolons), so we can remove them
+  // from the saved options
+  size_t DefaultsStringLength =
+      std::transform_reduce(DefaultExclusions.begin(), DefaultExclusions.end(),
+                            DefaultExclusions.size(), std::plus<>(),
+                            [](llvm::StringRef Name) { return Name.size(); });
+
+  std::string Serialized =
+      clang::tidy::utils::options::serializeStringList(ExcludedClasses);
+
+  Options.store(Opts, "ExcludeClasses",
+                Serialized.substr(0, Serialized.size() - DefaultsStringLength));
+}
+
+const CXXMethodDecl *findAlternative(const CXXRecordDecl *MatchedParent,
+                                     const CXXMethodDecl *MatchedOperator) {
+  for (const CXXMethodDecl *Method : MatchedParent->methods()) {
+    const bool CorrectName = Method->getNameInfo().getAsString() == "at";
+    if (!CorrectName)
+      continue;
+
+    const bool SameReturnType =
+        Method->getReturnType() == MatchedOperator->getReturnType();
+    if (!SameReturnType)
+      continue;
+
+    const bool SameNumberOfArguments =
+        Method->getNumParams() == MatchedOperator->getNumParams();
+    if (!SameNumberOfArguments)
+      continue;
+
+    for (unsigned ArgInd = 0; ArgInd < Method->getNumParams(); ArgInd++) {
+      const bool SameArgType =
+          Method->parameters()[ArgInd]->getOriginalType() ==
+          MatchedOperator->parameters()[ArgInd]->getOriginalType();
+      if (!SameArgType)
+        continue;
+    }
+
+    return Method;
+  }
+  return static_cast<CXXMethodDecl *>(nullptr);
+}
+
+void PreferAtOverSubscriptOperatorCheck::registerMatchers(MatchFinder *Finder) {
+  // Need a callExpr here to match CXXOperatorCallExpr ``(&a)->operator[](0)``
+  // and CXXMemberCallExpr ``a[0]``.
+  Finder->addMatcher(
+      callExpr(
+          callee(
+              cxxMethodDecl(hasOverloadedOperatorName("[]")).bind("operator")),
+          callee(cxxMethodDecl(hasParent(
+              cxxRecordDecl(hasMethod(hasName("at"))).bind("parent")))))
+          .bind("caller"),
+      this);
+}
+
+void PreferAtOverSubscriptOperatorCheck::check(
+    const MatchFinder::MatchResult &Result) {
+  const auto *MatchedExpr = Result.Nodes.getNodeAs<CallExpr>("caller");
+  const auto *MatchedOperator =
+      Result.Nodes.getNodeAs<CXXMethodDecl>("operator");
+  const auto *MatchedParent = Result.Nodes.getNodeAs<CXXRecordDecl>("parent");
+
+  std::string ClassIdentifier = MatchedParent->getQualifiedNameAsString();
+
+  if (std::find(ExcludedClasses.begin(), ExcludedClasses.end(),
+                ClassIdentifier) != ExcludedClasses.end())
+    return;
----------------
5chmidti wrote:

Prefer adding `matchers::matchesAnyListedName` from `clang-tools-extra/clang-tidy/utils/Matchers.h` to your matcher, instead of manually checking it like this (requires adding `::` in front of the exclusions in your test file, and other exclusions are prefixed as well (`map`, ...): https://github.com/llvm/llvm-project/blob/47f8b85b3d81ed3578cb3b8f80d69ce307e0c883/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringviewDataUsageCheck.cpp#L23).

https://github.com/llvm/llvm-project/blob/47f8b85b3d81ed3578cb3b8f80d69ce307e0c883/clang-tools-extra/clang-tidy/bugprone/NonZeroEnumToBoolConversionCheck.cpp#L63-L64

https://github.com/llvm/llvm-project/pull/95220


More information about the cfe-commits mailing list