376 lines · cpp
1//===--- OverridePureVirtuals.cpp --------------------------------*- 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-exception6//7//===----------------------------------------------------------------------===//8//9// Tweak to automatically generate stubs for pure virtual methods inherited from10// base classes.11//12// Purpose:13// - Simplifies making a derived class concrete by automating the creation of14// required method overrides from abstract bases.15//16// Tweak Summary:17//18// 1. Activation Conditions (prepare):19// - The tweak activates when the cursor is over a C++ class definition.20// - The class must be abstract (it, or its base classes, have unimplemented21// pure virtual functions).22// - It must also inherit from at least one other abstract class.23//24// 2. Identifying Missing Methods:25// - The tweak scans the inheritance hierarchy of the current class.26// - It identifies all unique pure virtual methods from base classes27// that are not yet implemented or overridden.28// - These missing methods are then grouped by their original access29// specifier (e.g., public, protected).30//31// 3. Code Generation and Insertion:32// - For each group of missing methods, stubs are inserted.33// - If an access specifier section (like `public:`) exists, stubs are34// inserted there; otherwise, a new section is created and appended.35// - Each generated stub includes the `override` keyword, a `// TODO:`36// comment, and a `static_assert(false, ...)` to force a compile-time37// error if the method remains unimplemented.38// - The base method's signature is adjusted (e.g., `virtual` and `= 0`39// are removed for the override).40//41// 4. Code Action Provided:42// - A single code action titled "Override pure virtual methods" is offered.43// - Applying this action results in a single source file modification44// containing all the generated method stubs.45//46// Example:47//48// class Base {49// public:50// virtual void publicMethod() = 0;51// protected:52// virtual auto privateMethod() const -> int = 0;53// };54//55// Before:56// // cursor here57// class Derived : public Base {}^;58//59// After:60//61// class Derived : public Base {62// public:63// void publicMethod() override {64// // TODO: Implement this pure virtual method.65// static_assert(false, "Method `publicMethod` is not implemented.");66// }67//68// protected:69// auto privateMethod() const -> int override {70// // TODO: Implement this pure virtual method.71// static_assert(false, "Method `privateMethod` is not implemented.");72// }73// };74//75//===----------------------------------------------------------------------===//76 77#include "refactor/Tweak.h"78#include "support/Token.h"79 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"89#include <string>90 91namespace clang {92namespace clangd {93namespace {94 95// This function removes the "virtual" and the "= 0" at the end;96// e.g.:97// "virtual void foo(int var = 0) = 0" // input.98// "void foo(int var = 0)" // output.99std::string removePureVirtualSyntax(const std::string &MethodDecl,100 const LangOptions &LangOpts) {101 assert(!MethodDecl.empty());102 103 TokenStream TS = lex(MethodDecl, LangOpts);104 105 std::string DeclString;106 for (const clangd::Token &Tk : TS.tokens()) {107 if (Tk.Kind == clang::tok::raw_identifier && Tk.text() == "virtual")108 continue;109 110 // If the ending two tokens are "= 0", we break here and we already have the111 // method's string without the pure virtual syntax.112 const auto &Next = Tk.next();113 if (Next.next().Kind == tok::eof && Tk.Kind == clang::tok::equal &&114 Next.text() == "0")115 break;116 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)121 DeclString += ' ';122 }123 // Trim the last whitespace.124 if (DeclString.back() == ' ')125 DeclString.pop_back();126 127 return DeclString;128}129 130class OverridePureVirtuals final : public Tweak {131public:132 const char *id() const final; // defined by REGISTER_TWEAK.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 {137 return CodeAction::QUICKFIX_KIND;138 }139 140private:141 // Stores the CXXRecordDecl of the class being modified.142 const CXXRecordDecl *CurrentDeclDef = nullptr;143 // Stores pure virtual methods that need overriding, grouped by their original144 // access specifier.145 llvm::MapVector<AccessSpecifier, llvm::SmallVector<const CXXMethodDecl *>>146 MissingMethodsByAccess;147 // Stores the source locations of existing access specifiers in CurrentDecl.148 llvm::MapVector<AccessSpecifier, SourceLocation> AccessSpecifierLocations;149 // Helper function to gather information before applying the tweak.150 void collectMissingPureVirtuals();151};152 153REGISTER_TWEAK(OverridePureVirtuals)154 155// Function to get all unique pure virtual methods from the entire156// base class hierarchy of CurrentDeclDef.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;162 163 if (!CurrentDeclDef || !CurrentDeclDef->getDefinition())164 return AllPureVirtualsInHierarchy;165 166 const clang::CXXRecordDecl *Def = CurrentDeclDef->getDefinition();167 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);173 }174 // Continue iterating through all bases.175 return true;176 });177 178 return AllPureVirtualsInHierarchy;179}180 181// Gets canonical declarations of methods already overridden or implemented in182// class D.183llvm::SetVector<const CXXMethodDecl *>184getImplementedOrOverriddenCanonicals(const CXXRecordDecl *D) {185 llvm::SetVector<const CXXMethodDecl *> ImplementedSet;186 for (const CXXMethodDecl *M : D->methods()) {187 // If M provides an implementation for any virtual method it overrides.188 // A method is an "implementation" if it's virtual and not pure.189 // Or if it directly overrides a base method.190 for (const CXXMethodDecl *OverriddenM : M->overridden_methods())191 ImplementedSet.insert(OverriddenM->getCanonicalDecl());192 }193 return ImplementedSet;194}195 196// Get the location of every colon of the `AccessSpecifier`.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();203 }204 return Locs;205}206 207bool hasAbstractBaseAncestor(const clang::CXXRecordDecl *CurrentDecl) {208 assert(CurrentDecl && CurrentDecl->getDefinition());209 210 return llvm::any_of(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();215 });216}217 218// The tweak is available if the selection is over an abstract C++ class219// definition that also inherits from at least one other abstract class.220bool OverridePureVirtuals::prepare(const Selection &Sel) {221 const SelectionTree::Node *Node = Sel.ASTSelection.commonAncestor();222 if (!Node)223 return false;224 225 // Make sure we have a definition.226 CurrentDeclDef = Node->ASTNode.get<CXXRecordDecl>();227 if (!CurrentDeclDef || !CurrentDeclDef->getDefinition())228 return false;229 230 // From now on, we should work with the definition.231 CurrentDeclDef = CurrentDeclDef->getDefinition();232 233 // Only offer for abstract classes with abstract bases.234 return CurrentDeclDef->isAbstract() &&235 hasAbstractBaseAncestor(CurrentDeclDef);236}237 238// Collects all pure virtual methods from base classes that `CurrentDeclDef` has239// not yet overridden, grouped by their original access specifier.240//241// Results are stored in `MissingMethodsByAccess` and `AccessSpecifierLocations`242// is also populated.243void OverridePureVirtuals::collectMissingPureVirtuals() {244 if (!CurrentDeclDef)245 return;246 247 AccessSpecifierLocations = getSpecifierLocations(CurrentDeclDef);248 MissingMethodsByAccess.clear();249 250 // Get all unique pure virtual methods from the entire base class hierarchy.251 llvm::SmallVector<const CXXMethodDecl *> AllPureVirtualsInHierarchy =252 getAllUniquePureVirtualsFromBaseHierarchy(CurrentDeclDef);253 254 // Get methods already implemented or overridden in CurrentDecl.255 const auto ImplementedOrOverriddenSet =256 getImplementedOrOverriddenCanonicals(CurrentDeclDef);257 258 // Filter AllPureVirtualsInHierarchy to find those not in259 // ImplementedOrOverriddenSet, which needs to be overriden.260 for (const CXXMethodDecl *BaseMethod : AllPureVirtualsInHierarchy) {261 bool AlreadyHandled = ImplementedOrOverriddenSet.contains(BaseMethod);262 if (!AlreadyHandled)263 MissingMethodsByAccess[BaseMethod->getAccess()].emplace_back(BaseMethod);264 }265}266 267std::string generateOverrideString(const CXXMethodDecl *Method,268 const LangOptions &LangOpts) {269 std::string MethodDecl;270 auto OS = llvm::raw_string_ostream(MethodDecl);271 Method->print(OS);272 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"277 " }",278 removePureVirtualSyntax(MethodDecl, LangOpts), Method->getName())279 .str();280}281 282// Free function to generate the string for a group of method overrides.283std::string generateOverridesStringForGroup(284 llvm::SmallVector<const CXXMethodDecl *> Methods,285 const LangOptions &LangOpts) {286 llvm::SmallVector<std::string> MethodsString;287 MethodsString.reserve(Methods.size());288 289 for (const CXXMethodDecl *Method : Methods) {290 MethodsString.emplace_back(generateOverrideString(Method, LangOpts));291 }292 293 return llvm::join(MethodsString, "\n") + '\n';294}295 296Expected<Tweak::Effect> OverridePureVirtuals::apply(const Selection &Sel) {297 // The correctness of this tweak heavily relies on the accurate population of298 // these members.299 collectMissingPureVirtuals();300 // The `prepare` should prevent this. If the prepare identifies an abstract301 // method, then is must have missing methods.302 assert(!MissingMethodsByAccess.empty());303 304 const auto &SM = Sel.AST->getSourceManager();305 const auto &LangOpts = Sel.AST->getLangOpts();306 307 tooling::Replacements EditReplacements;308 // Stores text for new access specifier sections that are not already present309 // in the class.310 // Example:311 // public: // ...312 // protected: // ...313 std::string NewSectionsToAppendText;314 315 for (const auto &[AS, Methods] : MissingMethodsByAccess) {316 assert(!Methods.empty());317 318 std::string MethodsGroupString =319 generateOverridesStringForGroup(Methods, LangOpts);320 321 auto *ExistingSpecLocIter = AccessSpecifierLocations.find(AS);322 bool ASExists = ExistingSpecLocIter != AccessSpecifierLocations.end();323 if (ASExists) {324 // Access specifier section already exists in the class.325 // Get location immediately *after* the colon.326 SourceLocation InsertLoc =327 ExistingSpecLocIter->second.getLocWithOffset(1);328 329 // Create a replacement to insert the method declarations.330 // The replacement is at InsertLoc, has length 0 (insertion), and uses331 // InsertionText.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));336 } else {337 // Access specifier section does not exist in the class.338 // These methods will be grouped into NewSectionsToAppendText and added339 // towards the end of the class definition.340 NewSectionsToAppendText +=341 getAccessSpelling(AS).str() + ':' + MethodsGroupString;342 }343 }344 345 // After processing all access specifiers, add any newly created sections346 // (stored in NewSectionsToAppendText) to the end of the class.347 if (!NewSectionsToAppendText.empty()) {348 // AppendLoc is the SourceLocation of the closing brace '}' of the class.349 // The replacement will insert text *before* this closing brace.350 SourceLocation AppendLoc = CurrentDeclDef->getBraceRange().getEnd();351 std::string FinalAppendText = std::move(NewSectionsToAppendText);352 353 if (!CurrentDeclDef->decls_empty() || !EditReplacements.empty()) {354 FinalAppendText = '\n' + FinalAppendText;355 }356 357 // Create a replacement to append the new sections.358 tooling::Replacement Rep(SM, AppendLoc, 0, FinalAppendText);359 if (auto Err = EditReplacements.add(Rep))360 return llvm::Expected<Tweak::Effect>(std::move(Err));361 }362 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());367 }368 369 // Return the collected replacements as the effect of this tweak.370 return Effect::mainFileEdit(SM, EditReplacements);371}372 373} // namespace374} // namespace clangd375} // namespace clang376