80#include "clang/AST/ASTContext.h"
81#include "clang/AST/DeclCXX.h"
82#include "clang/AST/Type.h"
83#include "clang/AST/TypeLoc.h"
84#include "clang/Basic/LLVM.h"
85#include "clang/Basic/SourceLocation.h"
86#include "clang/Tooling/Core/Replacement.h"
87#include "llvm/ADT/DenseSet.h"
88#include "llvm/Support/FormatVariadic.h"
99std::string removePureVirtualSyntax(
const std::string &MethodDecl,
100 const LangOptions &LangOpts) {
101 assert(!MethodDecl.empty());
105 std::string DeclString;
106 for (
const clangd::Token &Tk : TS.tokens()) {
107 if (Tk.Kind == clang::tok::raw_identifier && Tk.text() ==
"virtual")
112 const auto &Next = Tk.next();
113 if (Next.next().Kind == tok::eof && Tk.Kind == clang::tok::equal &&
117 DeclString += Tk.text();
118 if (Tk.Kind != tok::l_paren && Next.Kind != tok::comma &&
119 Next.Kind != tok::r_paren && Next.Kind != tok::l_paren)
123 if (DeclString.back() ==
' ')
124 DeclString.pop_back();
129class OverridePureVirtuals final :
public Tweak {
131 const char *id() const final;
132 bool prepare(const Selection &Sel) override;
133 Expected<Effect> apply(const Selection &Sel) override;
134 std::
string title()
const override {
return "Override pure virtual methods"; }
135 llvm::StringLiteral kind()
const override {
141 const CXXRecordDecl *CurrentDeclDef =
nullptr;
144 llvm::MapVector<AccessSpecifier, llvm::SmallVector<const CXXMethodDecl *>>
145 MissingMethodsByAccess;
147 llvm::MapVector<AccessSpecifier, SourceLocation> AccessSpecifierLocations;
149 void collectMissingPureVirtuals();
156llvm::SmallVector<const clang::CXXMethodDecl *>
157getAllUniquePureVirtualsFromBaseHierarchy(
158 const clang::CXXRecordDecl *CurrentDeclDef) {
159 llvm::SmallVector<const clang::CXXMethodDecl *> AllPureVirtualsInHierarchy;
160 llvm::DenseSet<const clang::CXXMethodDecl *> CanonicalPureVirtualsSeen;
162 if (!CurrentDeclDef || !CurrentDeclDef->getDefinition())
163 return AllPureVirtualsInHierarchy;
165 const clang::CXXRecordDecl *Def = CurrentDeclDef->getDefinition();
167 Def->forallBases([&](
const clang::CXXRecordDecl *BaseDefinition) {
168 for (
const clang::CXXMethodDecl *
Method : BaseDefinition->methods()) {
169 if (
Method->isPureVirtual() &&
170 CanonicalPureVirtualsSeen.insert(
Method->getCanonicalDecl()).second)
171 AllPureVirtualsInHierarchy.emplace_back(
Method);
177 return AllPureVirtualsInHierarchy;
182llvm::SetVector<const CXXMethodDecl *>
183getImplementedOrOverriddenCanonicals(
const CXXRecordDecl *D) {
184 llvm::SetVector<const CXXMethodDecl *> ImplementedSet;
185 for (
const CXXMethodDecl *M :
D->methods()) {
189 for (
const CXXMethodDecl *OverriddenM : M->overridden_methods())
190 ImplementedSet.insert(OverriddenM->getCanonicalDecl());
192 return ImplementedSet;
196llvm::MapVector<AccessSpecifier, SourceLocation>
197getSpecifierLocations(
const CXXRecordDecl *D) {
198 llvm::MapVector<AccessSpecifier, SourceLocation> Locs;
199 for (
auto *DeclNode :
D->decls()) {
200 if (
const auto *ASD = llvm::dyn_cast<AccessSpecDecl>(DeclNode))
201 Locs[ASD->getAccess()] = ASD->getColonLoc();
206bool hasAbstractBaseAncestor(
const clang::CXXRecordDecl *CurrentDecl) {
207 assert(CurrentDecl && CurrentDecl->getDefinition());
210 CurrentDecl->getDefinition()->bases(), [](CXXBaseSpecifier BaseSpec) {
211 const auto *D = BaseSpec.getType()->getAsCXXRecordDecl();
212 const auto *Def = D ? D->getDefinition() : nullptr;
213 return Def && Def->isAbstract();
219bool OverridePureVirtuals::prepare(
const Selection &Sel) {
220 const SelectionTree::Node *Node = Sel.ASTSelection.commonAncestor();
225 CurrentDeclDef = Node->ASTNode.get<CXXRecordDecl>();
226 if (!CurrentDeclDef || !CurrentDeclDef->getDefinition())
230 CurrentDeclDef = CurrentDeclDef->getDefinition();
233 return CurrentDeclDef->isAbstract() &&
234 hasAbstractBaseAncestor(CurrentDeclDef);
242void OverridePureVirtuals::collectMissingPureVirtuals() {
246 AccessSpecifierLocations = getSpecifierLocations(CurrentDeclDef);
247 MissingMethodsByAccess.clear();
250 llvm::SmallVector<const CXXMethodDecl *> AllPureVirtualsInHierarchy =
251 getAllUniquePureVirtualsFromBaseHierarchy(CurrentDeclDef);
254 const auto ImplementedOrOverriddenSet =
255 getImplementedOrOverriddenCanonicals(CurrentDeclDef);
259 for (
const CXXMethodDecl *BaseMethod : AllPureVirtualsInHierarchy) {
260 bool AlreadyHandled = ImplementedOrOverriddenSet.contains(BaseMethod);
262 MissingMethodsByAccess[BaseMethod->getAccess()].emplace_back(BaseMethod);
266std::string generateOverrideString(
const CXXMethodDecl *
Method,
267 const LangOptions &LangOpts) {
268 std::string MethodDecl;
269 auto OS = llvm::raw_string_ostream(MethodDecl);
272 return llvm::formatv(
273 "\n {0} override {{\n"
274 " // TODO: Implement this pure virtual method.\n"
275 " static_assert(false, \"Method `{1}` is not implemented.\");\n"
277 removePureVirtualSyntax(MethodDecl, LangOpts),
Method->getName())
282std::string generateOverridesStringForGroup(
283 llvm::SmallVector<const CXXMethodDecl *> Methods,
284 const LangOptions &LangOpts) {
285 llvm::SmallVector<std::string> MethodsString;
286 MethodsString.reserve(Methods.size());
288 for (
const CXXMethodDecl *
Method : Methods) {
289 MethodsString.emplace_back(generateOverrideString(
Method, LangOpts));
292 return llvm::join(MethodsString,
"\n") +
'\n';
295Expected<Tweak::Effect> OverridePureVirtuals::apply(
const Selection &Sel) {
298 collectMissingPureVirtuals();
301 assert(!MissingMethodsByAccess.empty());
303 const auto &SM = Sel.AST->getSourceManager();
304 const auto &LangOpts = Sel.AST->getLangOpts();
306 tooling::Replacements EditReplacements;
312 std::string NewSectionsToAppendText;
314 for (
const auto &[AS, Methods] : MissingMethodsByAccess) {
315 assert(!Methods.empty());
317 std::string MethodsGroupString =
318 generateOverridesStringForGroup(Methods, LangOpts);
320 auto *ExistingSpecLocIter = AccessSpecifierLocations.find(AS);
321 bool ASExists = ExistingSpecLocIter != AccessSpecifierLocations.end();
325 SourceLocation InsertLoc =
326 ExistingSpecLocIter->second.getLocWithOffset(1);
331 std::string InsertionText = MethodsGroupString;
332 tooling::Replacement Rep(SM, InsertLoc, 0, InsertionText);
333 if (
auto Err = EditReplacements.add(Rep))
334 return llvm::Expected<Tweak::Effect>(std::move(Err));
339 NewSectionsToAppendText +=
340 getAccessSpelling(AS).str() +
':' + MethodsGroupString;
346 if (!NewSectionsToAppendText.empty()) {
349 SourceLocation AppendLoc = CurrentDeclDef->getBraceRange().getEnd();
350 std::string FinalAppendText = std::move(NewSectionsToAppendText);
352 if (!CurrentDeclDef->decls_empty() || !EditReplacements.empty()) {
353 FinalAppendText =
'\n' + FinalAppendText;
357 tooling::Replacement Rep(SM, AppendLoc, 0, FinalAppendText);
358 if (
auto Err = EditReplacements.add(Rep))
359 return llvm::Expected<Tweak::Effect>(std::move(Err));
362 if (EditReplacements.empty()) {
363 return llvm::make_error<llvm::StringError>(
364 "No changes to apply (internal error or no methods generated).",
365 llvm::inconvertibleErrorCode());
369 return Effect::mainFileEdit(SM, EditReplacements);
#define REGISTER_TWEAK(Subclass)
A complete sequence of Tokens representing a source file.
An interface base for small context-sensitive refactoring actions.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
static void lex(llvm::StringRef Code, const LangOptions &LangOpts, llvm::function_ref< void(const syntax::Token &, const SourceManager &SM)> Action)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const llvm::StringLiteral QUICKFIX_KIND