80#include "clang/AST/ASTContext.h"
81#include "clang/AST/DeclCXX.h"
82#include "clang/AST/TypeBase.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 &&
120 Tk.Kind != tok::coloncolon && Next.Kind != tok::coloncolon)
124 if (DeclString.back() ==
' ')
125 DeclString.pop_back();
130class OverridePureVirtuals final :
public Tweak {
132 const char *id() const final;
133 bool prepare(const Selection &Sel) override;
134 Expected<Effect> apply(const Selection &Sel) override;
135 std::
string title()
const override {
return "Override pure virtual methods"; }
136 llvm::StringLiteral kind()
const override {
142 const CXXRecordDecl *CurrentDeclDef =
nullptr;
145 llvm::MapVector<AccessSpecifier, llvm::SmallVector<const CXXMethodDecl *>>
146 MissingMethodsByAccess;
148 llvm::MapVector<AccessSpecifier, SourceLocation> AccessSpecifierLocations;
150 void collectMissingPureVirtuals();
157llvm::SmallVector<const clang::CXXMethodDecl *>
158getAllUniquePureVirtualsFromBaseHierarchy(
159 const clang::CXXRecordDecl *CurrentDeclDef) {
160 llvm::SmallVector<const clang::CXXMethodDecl *> AllPureVirtualsInHierarchy;
161 llvm::DenseSet<const clang::CXXMethodDecl *> CanonicalPureVirtualsSeen;
163 if (!CurrentDeclDef || !CurrentDeclDef->getDefinition())
164 return AllPureVirtualsInHierarchy;
166 const clang::CXXRecordDecl *Def = CurrentDeclDef->getDefinition();
168 Def->forallBases([&](
const clang::CXXRecordDecl *BaseDefinition) {
169 for (
const clang::CXXMethodDecl *
Method : BaseDefinition->methods()) {
170 if (
Method->isPureVirtual() &&
171 CanonicalPureVirtualsSeen.insert(
Method->getCanonicalDecl()).second)
172 AllPureVirtualsInHierarchy.emplace_back(
Method);
178 return AllPureVirtualsInHierarchy;
183llvm::SetVector<const CXXMethodDecl *>
184getImplementedOrOverriddenCanonicals(
const CXXRecordDecl *D) {
185 llvm::SetVector<const CXXMethodDecl *> ImplementedSet;
186 for (
const CXXMethodDecl *M :
D->methods()) {
190 for (
const CXXMethodDecl *OverriddenM : M->overridden_methods())
191 ImplementedSet.insert(OverriddenM->getCanonicalDecl());
193 return ImplementedSet;
197llvm::MapVector<AccessSpecifier, SourceLocation>
198getSpecifierLocations(
const CXXRecordDecl *D) {
199 llvm::MapVector<AccessSpecifier, SourceLocation> Locs;
200 for (
auto *DeclNode :
D->decls()) {
201 if (
const auto *ASD = llvm::dyn_cast<AccessSpecDecl>(DeclNode))
202 Locs[ASD->getAccess()] = ASD->getColonLoc();
207bool hasAbstractBaseAncestor(
const clang::CXXRecordDecl *CurrentDecl) {
208 assert(CurrentDecl && CurrentDecl->getDefinition());
211 CurrentDecl->getDefinition()->bases(), [](CXXBaseSpecifier BaseSpec) {
212 const auto *D = BaseSpec.getType()->getAsCXXRecordDecl();
213 const auto *Def = D ? D->getDefinition() : nullptr;
214 return Def && Def->isAbstract();
220bool OverridePureVirtuals::prepare(
const Selection &Sel) {
221 const SelectionTree::Node *Node = Sel.ASTSelection.commonAncestor();
226 CurrentDeclDef = Node->ASTNode.get<CXXRecordDecl>();
227 if (!CurrentDeclDef || !CurrentDeclDef->getDefinition())
231 CurrentDeclDef = CurrentDeclDef->getDefinition();
234 return CurrentDeclDef->isAbstract() &&
235 hasAbstractBaseAncestor(CurrentDeclDef);
243void OverridePureVirtuals::collectMissingPureVirtuals() {
247 AccessSpecifierLocations = getSpecifierLocations(CurrentDeclDef);
248 MissingMethodsByAccess.clear();
251 llvm::SmallVector<const CXXMethodDecl *> AllPureVirtualsInHierarchy =
252 getAllUniquePureVirtualsFromBaseHierarchy(CurrentDeclDef);
255 const auto ImplementedOrOverriddenSet =
256 getImplementedOrOverriddenCanonicals(CurrentDeclDef);
260 for (
const CXXMethodDecl *BaseMethod : AllPureVirtualsInHierarchy) {
261 bool AlreadyHandled = ImplementedOrOverriddenSet.contains(BaseMethod);
263 MissingMethodsByAccess[BaseMethod->getAccess()].emplace_back(BaseMethod);
267std::string generateOverrideString(
const CXXMethodDecl *
Method,
268 const LangOptions &LangOpts) {
269 std::string MethodDecl;
270 auto OS = llvm::raw_string_ostream(MethodDecl);
273 return llvm::formatv(
274 "\n {0} override {{\n"
275 " // TODO: Implement this pure virtual method.\n"
276 " static_assert(false, \"Method `{1}` is not implemented.\");\n"
278 removePureVirtualSyntax(MethodDecl, LangOpts),
Method->getName())
283std::string generateOverridesStringForGroup(
284 llvm::SmallVector<const CXXMethodDecl *> Methods,
285 const LangOptions &LangOpts) {
286 llvm::SmallVector<std::string> MethodsString;
287 MethodsString.reserve(Methods.size());
289 for (
const CXXMethodDecl *
Method : Methods) {
290 MethodsString.emplace_back(generateOverrideString(
Method, LangOpts));
293 return llvm::join(MethodsString,
"\n") +
'\n';
296Expected<Tweak::Effect> OverridePureVirtuals::apply(
const Selection &Sel) {
299 collectMissingPureVirtuals();
302 assert(!MissingMethodsByAccess.empty());
304 const auto &SM = Sel.AST->getSourceManager();
305 const auto &LangOpts = Sel.AST->getLangOpts();
307 tooling::Replacements EditReplacements;
313 std::string NewSectionsToAppendText;
315 for (
const auto &[AS, Methods] : MissingMethodsByAccess) {
316 assert(!Methods.empty());
318 std::string MethodsGroupString =
319 generateOverridesStringForGroup(Methods, LangOpts);
321 auto *ExistingSpecLocIter = AccessSpecifierLocations.find(AS);
322 bool ASExists = ExistingSpecLocIter != AccessSpecifierLocations.end();
326 SourceLocation InsertLoc =
327 ExistingSpecLocIter->second.getLocWithOffset(1);
332 std::string InsertionText = MethodsGroupString;
333 tooling::Replacement Rep(SM, InsertLoc, 0, InsertionText);
334 if (
auto Err = EditReplacements.add(Rep))
335 return llvm::Expected<Tweak::Effect>(std::move(Err));
340 NewSectionsToAppendText +=
341 getAccessSpelling(AS).str() +
':' + MethodsGroupString;
347 if (!NewSectionsToAppendText.empty()) {
350 SourceLocation AppendLoc = CurrentDeclDef->getBraceRange().getEnd();
351 std::string FinalAppendText = std::move(NewSectionsToAppendText);
353 if (!CurrentDeclDef->decls_empty() || !EditReplacements.empty()) {
354 FinalAppendText =
'\n' + FinalAppendText;
358 tooling::Replacement Rep(SM, AppendLoc, 0, FinalAppendText);
359 if (
auto Err = EditReplacements.add(Rep))
360 return llvm::Expected<Tweak::Effect>(std::move(Err));
363 if (EditReplacements.empty()) {
364 return llvm::make_error<llvm::StringError>(
365 "No changes to apply (internal error or no methods generated).",
366 llvm::inconvertibleErrorCode());
370 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