18#include "clang/AST/ASTTypeTraits.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Stmt.h"
25#include "clang/Basic/SourceLocation.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/TokenKinds.h"
28#include "clang/Tooling/Core/Replacement.h"
29#include "clang/Tooling/Syntax/Tokens.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/Support/Casting.h"
33#include "llvm/Support/Error.h"
47const FunctionDecl *getSelectedFunction(
const SelectionTree::Node *SelNode) {
50 const DynTypedNode &AstNode = SelNode->ASTNode;
51 if (
const FunctionDecl *FD = AstNode.get<FunctionDecl>())
53 if (AstNode.get<CompoundStmt>() &&
55 if (
const SelectionTree::Node *P = SelNode->Parent)
56 return P->ASTNode.get<FunctionDecl>();
61std::optional<Path> getSourceFile(llvm::StringRef
FileName,
62 const Tweak::Selection &Sel) {
72std::optional<const DeclContext *>
73findContextForNS(llvm::StringRef TargetNS,
const DeclContext *CurContext) {
74 assert(TargetNS.empty() || TargetNS.ends_with(
"::"));
76 CurContext = CurContext->getEnclosingNamespaceContext();
78 if (TargetNS.empty()) {
79 while (!CurContext->isTranslationUnit())
80 CurContext = CurContext->getParent();
85 std::string TargetContextNS =
86 CurContext->isNamespace()
87 ? llvm::cast<NamespaceDecl>(CurContext)->getQualifiedNameAsString()
89 TargetContextNS.append(
"::");
91 llvm::StringRef CurrentContextNS(TargetContextNS);
94 if (!CurrentContextNS.starts_with(TargetNS))
97 while (CurrentContextNS != TargetNS) {
98 CurContext = CurContext->getParent();
101 CurrentContextNS = CurrentContextNS.take_front(
102 CurrentContextNS.drop_back(2).rfind(
"::") + 2);
110llvm::Expected<std::string>
111getFunctionSourceAfterReplacements(
const FunctionDecl *FD,
112 const tooling::Replacements &Replacements) {
113 const auto &SM = FD->getASTContext().getSourceManager();
115 SM, FD->getASTContext().getLangOpts(), FD->getSourceRange());
117 return error(
"Couldn't get range for function.");
118 assert(!FD->getDescribedFunctionTemplate() &&
119 "Define out-of-line doesn't apply to function templates.");
122 unsigned FuncBegin = SM.getFileOffset(OrigFuncRange->getBegin());
123 unsigned FuncEnd = Replacements.getShiftedCodePosition(
124 SM.getFileOffset(OrigFuncRange->getEnd()));
127 auto QualifiedFunc = tooling::applyAllReplacements(
128 SM.getBufferData(SM.getMainFileID()), Replacements);
130 return QualifiedFunc.takeError();
131 return QualifiedFunc->substr(FuncBegin, FuncEnd - FuncBegin + 1);
137llvm::Expected<tooling::Replacements>
138deleteTokensWithKind(
const syntax::TokenBuffer &TokBuf, tok::TokenKind
Kind,
139 SourceRange FromRange) {
140 tooling::Replacements DelKeywordCleanups;
141 llvm::Error Errors = llvm::Error::success();
142 bool FoundAny =
false;
143 for (
const auto &Tok : TokBuf.expandedTokens(FromRange)) {
144 if (Tok.kind() !=
Kind)
147 auto Spelling = TokBuf.spelledForExpanded(llvm::ArrayRef(Tok));
149 Errors = llvm::joinErrors(
151 error(
"define outline: couldn't remove `{0}` keyword.",
152 tok::getKeywordSpelling(
Kind)));
155 auto &SM = TokBuf.sourceManager();
156 CharSourceRange DelRange =
157 syntax::Token::range(SM, Spelling->front(), Spelling->back())
160 DelKeywordCleanups.add(tooling::Replacement(SM, DelRange,
"")))
161 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
164 Errors = llvm::joinErrors(
166 error(
"define outline: couldn't find `{0}` keyword to remove.",
167 tok::getKeywordSpelling(
Kind)));
171 return std::move(Errors);
172 return DelKeywordCleanups;
181llvm::Expected<std::string>
182getFunctionSourceCode(
const FunctionDecl *FD, llvm::StringRef TargetNamespace,
183 const syntax::TokenBuffer &TokBuf,
184 const HeuristicResolver *Resolver) {
185 auto &
AST = FD->getASTContext();
186 auto &SM =
AST.getSourceManager();
187 auto TargetContext = findContextForNS(TargetNamespace, FD->getDeclContext());
189 return error(
"define outline: couldn't find a context for target");
191 llvm::Error Errors = llvm::Error::success();
192 tooling::Replacements DeclarationCleanups;
198 [&](ReferenceLoc Ref) {
202 if (Ref.Qualifier || Ref.Targets.empty() || Ref.NameLoc.isMacroID())
205 if (Ref.NameLoc != FD->getReturnTypeSourceRange().getBegin() &&
206 Ref.NameLoc != FD->getLocation())
209 for (
const NamedDecl *ND : Ref.Targets) {
210 if (ND->getDeclContext() != Ref.Targets.front()->getDeclContext()) {
211 elog(
"Targets from multiple contexts: {0}, {1}",
212 printQualifiedName(*Ref.Targets.front()),
213 printQualifiedName(*ND));
217 const NamedDecl *ND = Ref.Targets.front();
218 const std::string Qualifier =
220 SM.getLocForStartOfFile(SM.getMainFileID()), ND);
221 if (
auto Err = DeclarationCleanups.add(
222 tooling::Replacement(SM, Ref.NameLoc, 0, Qualifier)))
223 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
232 if (
const auto *Destructor = llvm::dyn_cast<CXXDestructorDecl>(FD)) {
233 if (
auto Err = DeclarationCleanups.add(tooling::Replacement(
234 SM, Destructor->getLocation(), 0,
236 SM.getLocForStartOfFile(SM.getMainFileID()),
238 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
243 for (
const auto *PVD : FD->parameters()) {
244 if (!PVD->hasDefaultArg())
247 auto DelRange = CharSourceRange::getTokenRange(PVD->getDefaultArgRange());
249 auto Tokens = TokBuf.expandedTokens(PVD->getSourceRange())
250 .take_while([&SM, &DelRange](
const syntax::Token &Tok) {
251 return SM.isBeforeInTranslationUnit(
252 Tok.location(), DelRange.getBegin());
254 if (TokBuf.expandedTokens(DelRange.getAsRange()).front().kind() !=
259 llvm::find_if(llvm::reverse(Tokens), [](
const syntax::Token &Tok) {
260 return Tok.kind() == tok::equal;
262 assert(Tok != Tokens.rend());
263 DelRange.setBegin(Tok->location());
266 DeclarationCleanups.add(tooling::Replacement(SM, DelRange,
"")))
267 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
270 auto DelAttr = [&](
const Attr *
A) {
274 TokBuf.spelledForExpanded(TokBuf.expandedTokens(
A->getRange()));
275 assert(
A->getLocation().isValid());
276 if (!AttrTokens || AttrTokens->empty()) {
277 Errors = llvm::joinErrors(
278 std::move(Errors),
error(
"define outline: Can't move out of line as "
279 "function has a macro `{0}` specifier.",
283 CharSourceRange DelRange =
284 syntax::Token::range(SM, AttrTokens->front(), AttrTokens->back())
287 DeclarationCleanups.add(tooling::Replacement(SM, DelRange,
"")))
288 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
291 DelAttr(FD->getAttr<OverrideAttr>());
292 DelAttr(FD->getAttr<FinalAttr>());
294 auto DelKeyword = [&](tok::TokenKind
Kind, SourceRange FromRange) {
295 auto DelKeywords = deleteTokensWithKind(TokBuf,
Kind, FromRange);
297 Errors = llvm::joinErrors(std::move(Errors), DelKeywords.takeError());
300 DeclarationCleanups = DeclarationCleanups.merge(*DelKeywords);
303 if (FD->isInlineSpecified())
304 DelKeyword(tok::kw_inline, {FD->getBeginLoc(), FD->getLocation()});
305 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
306 if (MD->isVirtualAsWritten())
307 DelKeyword(tok::kw_virtual, {FD->getBeginLoc(), FD->getLocation()});
309 DelKeyword(tok::kw_static, {FD->getBeginLoc(), FD->getLocation()});
311 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
312 if (CD->isExplicit())
313 DelKeyword(tok::kw_explicit, {FD->getBeginLoc(), FD->getLocation()});
317 return std::move(Errors);
318 return getFunctionSourceAfterReplacements(FD, DeclarationCleanups);
321struct InsertionPoint {
330llvm::Expected<InsertionPoint> getInsertionPoint(llvm::StringRef Contents,
331 llvm::StringRef QualifiedName,
332 const LangOptions &LangOpts) {
335 assert(!Region.EligiblePoints.empty());
342 return Offset.takeError();
343 return InsertionPoint{Region.EnclosingNamespace, *
Offset};
349SourceRange getDeletionRange(
const FunctionDecl *FD,
350 const syntax::TokenBuffer &TokBuf) {
351 auto DeletionRange = FD->getBody()->getSourceRange();
352 if (
auto *CD = llvm::dyn_cast<CXXConstructorDecl>(FD)) {
355 SourceLocation InitStart;
357 for (
const auto *CInit : CD->inits()) {
359 if (CInit->getSourceOrder() != 0)
361 InitStart = CInit->getSourceLocation();
364 if (InitStart.isValid()) {
365 auto Toks = TokBuf.expandedTokens(CD->getSourceRange());
367 Toks = Toks.take_while([&TokBuf, &InitStart](
const syntax::Token &Tok) {
368 return TokBuf.sourceManager().isBeforeInTranslationUnit(Tok.location(),
373 llvm::find_if(llvm::reverse(Toks), [](
const syntax::Token &Tok) {
374 return Tok.kind() == tok::colon;
376 assert(Tok != Toks.rend());
377 DeletionRange.setBegin(Tok->location());
380 return DeletionRange;
399class DefineOutline :
public Tweak {
401 const char *id()
const override;
403 bool hidden()
const override {
return false; }
404 llvm::StringLiteral kind()
const override {
407 std::string title()
const override {
408 return "Move function body to out-of-line";
411 bool prepare(
const Selection &Sel)
override {
415 if (!
isHeaderFile(Sel.AST->getSourceManager().getFilename(Sel.Cursor),
416 Sel.AST->getLangOpts()))
419 Source = getSelectedFunction(Sel.ASTSelection.commonAncestor());
421 if (!Source || !Source->doesThisDeclarationHaveABody() ||
422 Source->isOutOfLine())
427 if (Source->getDescribedFunctionTemplate())
429 if (Source->getTemplateSpecializationInfo())
432 if (
auto *MD = llvm::dyn_cast<CXXMethodDecl>(Source)) {
435 if (MD->getParent()->isTemplated())
440 for (
const DeclContext *DC = MD->getParent(); DC; DC = DC->getParent()) {
441 if (
auto *ND = llvm::dyn_cast<NamedDecl>(DC)) {
442 if (ND->getDeclName().isEmpty())
454 Expected<Effect> apply(
const Selection &Sel)
override {
455 const SourceManager &SM = Sel.AST->getSourceManager();
456 auto CCFile = getSourceFile(Sel.AST->tuPath(), Sel);
459 return error(
"Couldn't find a suitable implementation file.");
460 assert(Sel.FS &&
"FS Must be set in apply");
461 auto Buffer = Sel.FS->getBufferForFile(*CCFile);
465 return llvm::errorCodeToError(Buffer.getError());
466 auto Contents = Buffer->get()->getBuffer();
467 auto InsertionPoint = getInsertionPoint(
468 Contents, Source->getQualifiedNameAsString(), Sel.AST->getLangOpts());
470 return InsertionPoint.takeError();
472 auto FuncDef = getFunctionSourceCode(
473 Source, InsertionPoint->EnclosingNamespace, Sel.AST->getTokens(),
474 Sel.AST->getHeuristicResolver());
476 return FuncDef.takeError();
478 SourceManagerForFile SMFF(*CCFile, Contents);
479 const tooling::Replacement InsertFunctionDef(
480 *CCFile, InsertionPoint->Offset, 0, *FuncDef);
481 auto Effect = Effect::mainFileEdit(
482 SMFF.get(), tooling::Replacements(InsertFunctionDef));
484 return Effect.takeError();
486 tooling::Replacements HeaderUpdates(tooling::Replacement(
487 Sel.AST->getSourceManager(),
489 SM, Sel.AST->getLangOpts(),
490 getDeletionRange(Source, Sel.AST->getTokens()))),
493 if (Source->isInlineSpecified()) {
495 deleteTokensWithKind(Sel.AST->getTokens(), tok::kw_inline,
496 {Source->getBeginLoc(), Source->getLocation()});
498 return DelInline.takeError();
499 HeaderUpdates = HeaderUpdates.merge(*DelInline);
502 auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
504 return HeaderFE.takeError();
506 Effect->ApplyEdits.try_emplace(HeaderFE->first,
507 std::move(HeaderFE->second));
508 return std::move(*Effect);
512 const FunctionDecl *Source =
nullptr;
std::optional< std::string > EnclosingNamespace
#define REGISTER_TWEAK(Subclass)
std::optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
std::string getQualification(ASTContext &Context, const DeclContext *DestContext, SourceLocation InsertionPoint, const NamedDecl *ND)
Gets the nested name specifier necessary for spelling ND in DestContext, at InsertionPoint.
void findExplicitReferences(const Stmt *S, llvm::function_ref< void(ReferenceLoc)> Out, const HeuristicResolver *Resolver)
Recursively traverse S and report all references explicitly written in the code.
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
EligibleRegion getEligiblePoints(llvm::StringRef Code, llvm::StringRef FullyQualifiedName, const LangOptions &LangOpts)
Returns most eligible region to insert a definition for FullyQualifiedName in the Code.
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
std::optional< Path > getCorrespondingHeaderOrSource(PathRef OriginalFile, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS)
Given a header file, returns the best matching source file, and vice visa.
bool isHeaderFile(llvm::StringRef FileName, std::optional< LangOptions > LangOpts)
Infers whether this is a header from the FileName and LangOpts (if presents).
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const llvm::StringLiteral REFACTOR_KIND