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,
const DeclContext *TargetContext,
183 const syntax::TokenBuffer &TokBuf,
184 const HeuristicResolver *Resolver) {
185 auto &
AST = FD->getASTContext();
186 auto &SM =
AST.getSourceManager();
188 llvm::Error Errors = llvm::Error::success();
189 tooling::Replacements DeclarationCleanups;
195 [&](ReferenceLoc Ref) {
199 if (Ref.Qualifier || Ref.Targets.empty() || Ref.NameLoc.isMacroID())
202 if (Ref.NameLoc != FD->getReturnTypeSourceRange().getBegin() &&
203 Ref.NameLoc != FD->getLocation())
206 for (
const NamedDecl *ND : Ref.Targets) {
207 if (ND->getDeclContext() != Ref.Targets.front()->getDeclContext()) {
208 elog(
"Targets from multiple contexts: {0}, {1}",
209 printQualifiedName(*Ref.Targets.front()),
210 printQualifiedName(*ND));
214 const NamedDecl *ND = Ref.Targets.front();
215 const std::string Qualifier =
217 SM.getLocForStartOfFile(SM.getMainFileID()), ND);
218 if (
auto Err = DeclarationCleanups.add(
219 tooling::Replacement(SM, Ref.NameLoc, 0, Qualifier)))
220 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
229 if (
const auto *Destructor = llvm::dyn_cast<CXXDestructorDecl>(FD)) {
230 if (
auto Err = DeclarationCleanups.add(tooling::Replacement(
231 SM, Destructor->getLocation(), 0,
233 SM.getLocForStartOfFile(SM.getMainFileID()),
235 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
240 for (
const auto *PVD : FD->parameters()) {
241 if (!PVD->hasDefaultArg())
244 auto DelRange = CharSourceRange::getTokenRange(PVD->getDefaultArgRange());
246 auto Tokens = TokBuf.expandedTokens(PVD->getSourceRange())
247 .take_while([&SM, &DelRange](
const syntax::Token &Tok) {
248 return SM.isBeforeInTranslationUnit(
249 Tok.location(), DelRange.getBegin());
251 if (TokBuf.expandedTokens(DelRange.getAsRange()).front().kind() !=
256 llvm::find_if(llvm::reverse(Tokens), [](
const syntax::Token &Tok) {
257 return Tok.kind() == tok::equal;
259 assert(Tok != Tokens.rend());
260 DelRange.setBegin(Tok->location());
263 DeclarationCleanups.add(tooling::Replacement(SM, DelRange,
"")))
264 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
267 auto DelAttr = [&](
const Attr *
A) {
271 TokBuf.spelledForExpanded(TokBuf.expandedTokens(
A->getRange()));
272 assert(
A->getLocation().isValid());
273 if (!AttrTokens || AttrTokens->empty()) {
274 Errors = llvm::joinErrors(
275 std::move(Errors),
error(
"define outline: Can't move out of line as "
276 "function has a macro `{0}` specifier.",
280 CharSourceRange DelRange =
281 syntax::Token::range(SM, AttrTokens->front(), AttrTokens->back())
284 DeclarationCleanups.add(tooling::Replacement(SM, DelRange,
"")))
285 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
288 DelAttr(FD->getAttr<OverrideAttr>());
289 DelAttr(FD->getAttr<FinalAttr>());
291 auto DelKeyword = [&](tok::TokenKind
Kind, SourceRange FromRange) {
292 auto DelKeywords = deleteTokensWithKind(TokBuf,
Kind, FromRange);
294 Errors = llvm::joinErrors(std::move(Errors), DelKeywords.takeError());
297 DeclarationCleanups = DeclarationCleanups.merge(*DelKeywords);
300 if (FD->isInlineSpecified())
301 DelKeyword(tok::kw_inline, {FD->getBeginLoc(), FD->getLocation()});
302 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
303 if (MD->isVirtualAsWritten())
304 DelKeyword(tok::kw_virtual, {FD->getBeginLoc(), FD->getLocation()});
306 DelKeyword(tok::kw_static, {FD->getBeginLoc(), FD->getLocation()});
308 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
309 if (CD->isExplicit())
310 DelKeyword(tok::kw_explicit, {FD->getBeginLoc(), FD->getLocation()});
314 return std::move(Errors);
315 return getFunctionSourceAfterReplacements(FD, DeclarationCleanups);
318struct InsertionPoint {
326SourceRange getDeletionRange(
const FunctionDecl *FD,
327 const syntax::TokenBuffer &TokBuf) {
328 auto DeletionRange = FD->getBody()->getSourceRange();
329 if (
auto *CD = llvm::dyn_cast<CXXConstructorDecl>(FD)) {
332 SourceLocation InitStart;
334 for (
const auto *CInit : CD->inits()) {
336 if (CInit->getSourceOrder() != 0)
338 InitStart = CInit->getSourceLocation();
341 if (InitStart.isValid()) {
342 auto Toks = TokBuf.expandedTokens(CD->getSourceRange());
344 Toks = Toks.take_while([&TokBuf, &InitStart](
const syntax::Token &Tok) {
345 return TokBuf.sourceManager().isBeforeInTranslationUnit(Tok.location(),
350 llvm::find_if(llvm::reverse(Toks), [](
const syntax::Token &Tok) {
351 return Tok.kind() == tok::colon;
353 assert(Tok != Toks.rend());
354 DeletionRange.setBegin(Tok->location());
357 return DeletionRange;
376class DefineOutline :
public Tweak {
378 const char *id()
const override;
380 bool hidden()
const override {
return false; }
381 llvm::StringLiteral kind()
const override {
384 std::string title()
const override {
385 return "Move function body to out-of-line";
388 bool prepare(
const Selection &Sel)
override {
389 SameFile = !
isHeaderFile(Sel.AST->tuPath(), Sel.AST->getLangOpts());
390 Source = getSelectedFunction(Sel.ASTSelection.commonAncestor());
393 if (!Source || !Source->doesThisDeclarationHaveABody() ||
394 Source->isOutOfLine())
399 if (Source->getDescribedFunctionTemplate())
401 if (Source->getTemplateSpecializationInfo())
404 auto *MD = llvm::dyn_cast<CXXMethodDecl>(Source);
412 if (MD->getParent()->isTemplated())
417 for (
const DeclContext *DC = MD->getParent(); DC; DC = DC->getParent()) {
418 if (
auto *ND = llvm::dyn_cast<NamedDecl>(DC)) {
419 if (ND->getDeclName().isEmpty() &&
420 (!SameFile || !llvm::dyn_cast<NamespaceDecl>(ND)))
431 Expected<Effect> apply(
const Selection &Sel)
override {
432 const SourceManager &SM = Sel.AST->getSourceManager();
433 auto CCFile = SameFile ? Sel.AST->tuPath().str()
434 : getSourceFile(Sel.AST->tuPath(), Sel);
436 return error(
"Couldn't find a suitable implementation file.");
437 assert(Sel.FS &&
"FS Must be set in apply");
438 auto Buffer = Sel.FS->getBufferForFile(*CCFile);
442 return llvm::errorCodeToError(Buffer.getError());
443 auto Contents = Buffer->get()->getBuffer();
444 auto InsertionPoint = getInsertionPoint(Contents, Sel);
446 return InsertionPoint.takeError();
448 auto FuncDef = getFunctionSourceCode(
449 Source, InsertionPoint->EnclosingNamespace, Sel.AST->getTokens(),
450 Sel.AST->getHeuristicResolver());
452 return FuncDef.takeError();
454 SourceManagerForFile SMFF(*CCFile, Contents);
455 const tooling::Replacement InsertFunctionDef(
456 *CCFile, InsertionPoint->Offset, 0, *FuncDef);
457 auto Effect = Effect::mainFileEdit(
458 SMFF.get(), tooling::Replacements(InsertFunctionDef));
460 return Effect.takeError();
462 tooling::Replacements HeaderUpdates(tooling::Replacement(
463 Sel.AST->getSourceManager(),
465 SM, Sel.AST->getLangOpts(),
466 getDeletionRange(Source, Sel.AST->getTokens()))),
469 if (Source->isInlineSpecified()) {
471 deleteTokensWithKind(Sel.AST->getTokens(), tok::kw_inline,
472 {Source->getBeginLoc(), Source->getLocation()});
474 return DelInline.takeError();
475 HeaderUpdates = HeaderUpdates.merge(*DelInline);
479 tooling::Replacements &R = Effect->ApplyEdits[*CCFile].Replacements;
480 R = R.merge(HeaderUpdates);
482 auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
484 return HeaderFE.takeError();
485 Effect->ApplyEdits.try_emplace(HeaderFE->first,
486 std::move(HeaderFE->second));
488 return std::move(*Effect);
500 llvm::Expected<InsertionPoint> getInsertionPoint(llvm::StringRef Contents,
501 const Selection &Sel) {
506 auto *Klass = Source->getDeclContext()->getOuterLexicalRecordContext();
508 return error(
"moving to same file not supported for free functions");
509 const SourceLocation EndLoc = Klass->getBraceRange().getEnd();
510 const auto &TokBuf = Sel.AST->getTokens();
511 auto Tokens = TokBuf.expandedTokens();
512 auto It = llvm::lower_bound(
513 Tokens, EndLoc, [](
const syntax::Token &Tok, SourceLocation EndLoc) {
514 return Tok.location() < EndLoc;
516 while (It != Tokens.end()) {
517 if (It->kind() != tok::semi) {
521 unsigned Offset = Sel.AST->getSourceManager()
522 .getDecomposedLoc(It->endLocation())
524 return InsertionPoint{Klass->getEnclosingNamespaceContext(),
Offset};
527 "failed to determine insertion location: no end of class found");
531 Contents, Source->getQualifiedNameAsString(), Sel.AST->getLangOpts());
533 assert(!Region.EligiblePoints.empty());
536 return Offset.takeError();
539 findContextForNS(Region.EnclosingNamespace, Source->getDeclContext());
541 return error(
"define outline: couldn't find a context for target");
543 return InsertionPoint{*TargetContext, *
Offset};
547 const FunctionDecl *Source =
nullptr;
548 bool SameFile =
false;
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