[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)
Julian Schmidt via cfe-commits
cfe-commits at lists.llvm.org
Sat Nov 9 05:19:46 PST 2024
================
@@ -0,0 +1,62 @@
+//===--- IncorrectEnableSharedFromThisCheck.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 "IncorrectEnableSharedFromThisCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void IncorrectEnableSharedFromThisCheck::registerMatchers(MatchFinder *Finder) {
+ const auto EnableSharedFromThis =
+ cxxRecordDecl(hasName("enable_shared_from_this"), isInStdNamespace());
+ const auto QType = hasCanonicalType(hasDeclaration(
+ cxxRecordDecl(
+ anyOf(EnableSharedFromThis.bind("enable_rec"),
+ cxxRecordDecl(hasAnyBase(cxxBaseSpecifier(
+ isPublic(), hasType(hasCanonicalType(
+ hasDeclaration(EnableSharedFromThis))))))))
+ .bind("base_rec")));
+ Finder->addMatcher(
+ cxxRecordDecl(
+ hasDirectBase(cxxBaseSpecifier(unless(isPublic()), hasType(QType))
+ .bind("base")))
+ .bind("derived"),
+ this);
+}
+
+void IncorrectEnableSharedFromThisCheck::check(
+ const MatchFinder::MatchResult &Result) {
+ const auto *BaseSpec = Result.Nodes.getNodeAs<CXXBaseSpecifier>("base");
+ const auto *Base = Result.Nodes.getNodeAs<CXXRecordDecl>("base_rec");
+ const auto *Derived = Result.Nodes.getNodeAs<CXXRecordDecl>("derived");
+ const bool IsEnableSharedFromThisDirectBase =
+ Result.Nodes.getNodeAs<CXXRecordDecl>("enable_rec") == Base;
+ const SourceRange ReplacementRange = BaseSpec->getSourceRange();
+ const std::string ReplacementString =
+ // BaseSpec->getType().getAsString() results in
+ // std::enable_shared_from_this<ClassName> or
+ // alias/typedefs of std::enable_shared_from_this<ClassName>
+ "public " + BaseSpec->getType().getAsString();
----------------
5chmidti wrote:
I only know of https://clang.llvm.org/docs/InternalsManual.html#sourcerange-and-charsourcerange, which is a rather short description.
This is essentially saying: at the location (range), if there is a written access specifier, consider the range to be a token range (which will include the access specifier token in the range to be replaced), and if there is no access specifier written it is a character range (of size 0, so the replacement acts as an insertion).
---
nit: I forgot you can pass a single location to `SourceRange()`, and it will duplicate the location internally for begin and end.
https://github.com/llvm/llvm-project/pull/102299
More information about the cfe-commits
mailing list