19#include "clang/AST/ASTTypeTraits.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclTemplate.h"
25#include "clang/AST/Stmt.h"
26#include "clang/Basic/AttributeCommonInfo.h"
27#include "clang/Basic/SourceLocation.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TokenKinds.h"
30#include "clang/Tooling/Core/Replacement.h"
31#include "clang/Tooling/Syntax/Tokens.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/Error.h"
54 const DynTypedNode &AstNode = SelNode->
ASTNode;
55 if (
const FunctionDecl *FD = AstNode.get<FunctionDecl>())
57 if (AstNode.get<CompoundStmt>() &&
60 return P->ASTNode.get<FunctionDecl>();
65std::optional<Path> getSourceFile(llvm::StringRef FileName,
76std::optional<const DeclContext *>
77findContextForNS(llvm::StringRef TargetNS,
const DeclContext *CurContext) {
78 assert(TargetNS.empty() || TargetNS.ends_with(
"::"));
80 CurContext = CurContext->getEnclosingNamespaceContext();
82 if (TargetNS.empty()) {
83 while (!CurContext->isTranslationUnit())
84 CurContext = CurContext->getParent();
89 std::string TargetContextNS =
90 CurContext->isNamespace()
91 ? llvm::cast<NamespaceDecl>(CurContext)->getQualifiedNameAsString()
93 TargetContextNS.append(
"::");
95 llvm::StringRef CurrentContextNS(TargetContextNS);
98 if (!CurrentContextNS.starts_with(TargetNS))
101 while (CurrentContextNS != TargetNS) {
102 CurContext = CurContext->getParent();
105 CurrentContextNS = CurrentContextNS.take_front(
106 CurrentContextNS.drop_back(2).rfind(
"::") + 2);
114llvm::Expected<std::string>
115getFunctionSourceAfterReplacements(
const FunctionDecl *FD,
116 const tooling::Replacements &Replacements,
117 bool TargetFileIsHeader) {
118 const auto &SM = FD->getASTContext().getSourceManager();
120 SM, FD->getASTContext().getLangOpts(), FD->getSourceRange());
122 return error(
"Couldn't get range for function.");
125 unsigned FuncBegin = SM.getFileOffset(OrigFuncRange->getBegin());
126 unsigned FuncEnd = Replacements.getShiftedCodePosition(
127 SM.getFileOffset(OrigFuncRange->getEnd()));
130 auto QualifiedFunc = tooling::applyAllReplacements(
131 SM.getBufferData(SM.getMainFileID()), Replacements);
133 return QualifiedFunc.takeError();
135 auto Source = QualifiedFunc->substr(FuncBegin, FuncEnd - FuncBegin + 1);
136 std::string TemplatePrefix;
137 auto AddToTemplatePrefixIfApplicable = [&](
const Decl *
D) {
138 const TemplateParameterList *Params =
D->getDescribedTemplateParams();
141 for (Decl *P : *Params) {
142 if (
auto *TTP = dyn_cast<TemplateTypeParmDecl>(P))
143 TTP->removeDefaultArgument();
144 else if (
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
145 NTTP->removeDefaultArgument();
146 else if (
auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(P))
147 TTPD->removeDefaultArgument();
150 llvm::raw_string_ostream Stream(S);
151 Params->print(Stream, FD->getASTContext());
154 TemplatePrefix.insert(0, S);
156 AddToTemplatePrefixIfApplicable(FD);
157 if (
auto *
MD = llvm::dyn_cast<CXXMethodDecl>(FD)) {
158 for (
const CXXRecordDecl *Parent =
MD->getParent(); Parent;
160 llvm::dyn_cast_or_null<const CXXRecordDecl>(Parent->getParent())) {
161 AddToTemplatePrefixIfApplicable(Parent);
165 if (TargetFileIsHeader)
166 Source.insert(0,
"inline ");
167 if (!TemplatePrefix.empty())
168 Source.insert(0, TemplatePrefix);
169 if (!FD->hasBody() && !FD->isExplicitlyDefaulted()) {
172 if (!FD->getReturnType()->isVoidType())
173 Source +=
" return {}; ";
183llvm::Expected<tooling::Replacements>
184deleteTokensWithKind(
const syntax::TokenBuffer &TokBuf, tok::TokenKind Kind,
185 SourceRange FromRange) {
186 tooling::Replacements DelKeywordCleanups;
187 llvm::Error Errors = llvm::Error::success();
188 bool FoundAny =
false;
189 for (
const auto &Tok : TokBuf.expandedTokens(FromRange)) {
190 if (Tok.kind() != Kind)
193 auto Spelling = TokBuf.spelledForExpanded(llvm::ArrayRef(Tok));
195 Errors = llvm::joinErrors(
197 error(
"define outline: couldn't remove `{0}` keyword.",
198 tok::getKeywordSpelling(Kind)));
201 auto &SM = TokBuf.sourceManager();
202 CharSourceRange DelRange =
203 syntax::Token::range(SM, Spelling->front(), Spelling->back())
206 DelKeywordCleanups.add(tooling::Replacement(SM, DelRange,
"")))
207 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
210 Errors = llvm::joinErrors(
212 error(
"define outline: couldn't find `{0}` keyword to remove.",
213 tok::getKeywordSpelling(Kind)));
217 return std::move(Errors);
218 return DelKeywordCleanups;
224template <
typename Iterator>
225Iterator skipTokenPair(Iterator Begin, Iterator End, tok::TokenKind StartKind,
226 tok::TokenKind EndKind) {
228 for (
auto It = Begin; It != End; ++It) {
229 if (It->kind() == StartKind) {
231 }
else if (It->kind() == EndKind) {
245llvm::Error dropAttributes(
const syntax::TokenBuffer &TokBuf,
246 const FunctionDecl *FD,
247 tooling::Replacements &DeclarationCleanups) {
248 llvm::Error Errors = llvm::Error::success();
256 if (FD->isMultiVersion() || FD->hasAttr<EnableIfAttr>() ||
257 FD->hasAttr<OverloadableAttr>()) {
261 for (
const Attr *A : FD->attrs()) {
265 if (
A->isImplicit() ||
A->isInherited())
267 if (!isa<InheritableAttr>(A))
271 const SourceManager &SM = TokBuf.sourceManager();
274 const Stmt *Body = FD->getBody();
278 auto FDTokens = TokBuf.spelledForExpanded(
279 TokBuf.expandedTokens({FD->getBeginLoc(), Body->getBeginLoc()}));
285 for (
const Attr *A : FD->attrs()) {
287 llvm::SmallVector<tok::TokenKind> LeftDelimiter, RightDelimiter;
288 switch (
A->getSyntax()) {
289 case AttributeCommonInfo::AS_GNU:
291 LeftDelimiter.assign({tok::kw___attribute, tok::l_paren, tok::l_paren});
292 RightDelimiter.assign({tok::r_paren, tok::r_paren});
294 case AttributeCommonInfo::AS_CXX11:
295 case AttributeCommonInfo::AS_C23:
297 LeftDelimiter.assign({tok::l_square, tok::l_square});
298 RightDelimiter.assign({tok::r_square, tok::r_square});
300 case AttributeCommonInfo::AS_Declspec:
302 LeftDelimiter.assign({tok::kw___declspec, tok::l_paren});
303 RightDelimiter.assign({tok::r_paren});
311 if (LeftDelimiter.empty() || RightDelimiter.empty())
315 TokBuf.spelledForExpanded(TokBuf.expandedTokens(
A->getRange()));
317 if (!FDTokens.has_value() || !AttrTokens.has_value() ||
318 !SM.isPointWithin(
A->getLocation(), FDTokens->front().location(),
319 FDTokens->back().location()))
322 CharSourceRange DelRange;
325 for (
auto It = AttrTokens->end(), E = FDTokens->end(); It != E; ++It) {
329 if (It->kind() == tok::l_paren) {
330 It = skipTokenPair(It, E, tok::l_paren, tok::r_paren);
335 if (std::distance(It, E) <
static_cast<long>(RightDelimiter.size()))
339 llvm::ArrayRef<syntax::Token> Candidate(It, RightDelimiter.size());
341 if (llvm::equal(Candidate, RightDelimiter,
342 [](
const auto &Tok,
const auto &TokKindDel) {
343 return Tok.kind() == TokKindDel;
345 DelRange.setEnd(Candidate.back().endLocation());
351 for (
auto It = AttrTokens->begin(), E = FDTokens->begin(); It != E; --It) {
352 if (std::distance(E, It) <
static_cast<long>(LeftDelimiter.size()))
355 llvm::ArrayRef<syntax::Token> Candidate(
356 std::prev(It, LeftDelimiter.size()), LeftDelimiter.size());
358 if (llvm::equal(Candidate, LeftDelimiter,
359 [](
const auto &Tok,
const auto &TokKindDel) {
360 return Tok.kind() == TokKindDel;
362 DelRange.setBegin(Candidate.front().location());
367 if (DelRange.isValid()) {
369 DeclarationCleanups.add(tooling::Replacement(SM, DelRange,
"")))
370 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
381llvm::Expected<std::string>
382getFunctionSourceCode(
const FunctionDecl *FD,
const DeclContext *TargetContext,
383 const syntax::TokenBuffer &TokBuf,
384 const HeuristicResolver *Resolver,
385 bool TargetFileIsHeader) {
386 auto &
AST = FD->getASTContext();
387 auto &SM =
AST.getSourceManager();
389 llvm::Error Errors = llvm::Error::success();
390 tooling::Replacements DeclarationCleanups;
400 if (
Ref.Qualifier ||
Ref.Targets.empty() ||
Ref.NameLoc.isMacroID())
403 if (
auto ReturnTypeRange = FD->getReturnTypeSourceRange();
404 Ref.NameLoc != FD->getLocation() &&
405 (ReturnTypeRange.isInvalid() ||
406 SM.isBeforeInTranslationUnit(
Ref.NameLoc,
407 ReturnTypeRange.getBegin()) ||
408 SM.isBeforeInTranslationUnit(ReturnTypeRange.getEnd(),
412 for (
const NamedDecl *ND :
Ref.Targets) {
413 if (ND->getKind() == Decl::TemplateTypeParm)
415 if (ND->getDeclContext() !=
Ref.Targets.front()->getDeclContext()) {
416 elog(
"Targets from multiple contexts: {0}, {1}",
422 const NamedDecl *ND =
Ref.Targets.front();
423 std::string Qualifier =
425 SM.getLocForStartOfFile(SM.getMainFileID()), ND);
426 if (ND->getDeclContext()->isDependentContext() &&
427 llvm::isa<TypeDecl>(ND)) {
428 Qualifier.insert(0,
"typename ");
430 if (
auto Err = DeclarationCleanups.add(
431 tooling::Replacement(SM,
Ref.NameLoc, 0, Qualifier)))
432 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
441 if (
const auto *Destructor = llvm::dyn_cast<CXXDestructorDecl>(FD)) {
442 if (
auto Err = DeclarationCleanups.add(tooling::Replacement(
443 SM, Destructor->getLocation(), 0,
445 SM.getLocForStartOfFile(SM.getMainFileID()),
447 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
452 for (
const auto *PVD : FD->parameters()) {
453 if (!PVD->hasDefaultArg())
456 auto DelRange = CharSourceRange::getTokenRange(PVD->getDefaultArgRange());
458 auto Tokens = TokBuf.expandedTokens(PVD->getSourceRange())
459 .take_while([&SM, &DelRange](
const syntax::Token &Tok) {
460 return SM.isBeforeInTranslationUnit(
461 Tok.location(), DelRange.getBegin());
463 if (TokBuf.expandedTokens(DelRange.getAsRange()).front().kind() !=
468 llvm::find_if(llvm::reverse(Tokens), [](
const syntax::Token &Tok) {
469 return Tok.kind() == tok::equal;
471 assert(Tok != Tokens.rend());
472 DelRange.setBegin(Tok->location());
475 DeclarationCleanups.add(tooling::Replacement(SM, DelRange,
"")))
476 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
479 auto DelAttr = [&](
const Attr *
A) {
483 TokBuf.spelledForExpanded(TokBuf.expandedTokens(
A->getRange()));
484 assert(
A->getLocation().isValid());
485 if (!AttrTokens || AttrTokens->empty()) {
486 Errors = llvm::joinErrors(
487 std::move(Errors),
error(
"define outline: Can't move out of line as "
488 "function has a macro `{0}` specifier.",
492 CharSourceRange DelRange =
493 syntax::Token::range(SM, AttrTokens->front(), AttrTokens->back())
496 DeclarationCleanups.add(tooling::Replacement(SM, DelRange,
"")))
497 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
500 DelAttr(FD->getAttr<OverrideAttr>());
501 DelAttr(FD->getAttr<FinalAttr>());
503 auto DelKeyword = [&](tok::TokenKind Kind, SourceRange FromRange) {
504 auto DelKeywords = deleteTokensWithKind(TokBuf, Kind, FromRange);
506 Errors = llvm::joinErrors(std::move(Errors), DelKeywords.takeError());
509 DeclarationCleanups = DeclarationCleanups.merge(*DelKeywords);
512 if (FD->isInlineSpecified())
513 DelKeyword(tok::kw_inline, {FD->getBeginLoc(), FD->getLocation()});
514 if (
const auto *
MD = dyn_cast<CXXMethodDecl>(FD)) {
515 if (
MD->isVirtualAsWritten())
516 DelKeyword(tok::kw_virtual, {FD->getBeginLoc(), FD->getLocation()});
518 DelKeyword(tok::kw_static, {FD->getBeginLoc(), FD->getLocation()});
520 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
521 if (CD->isExplicit())
522 DelKeyword(tok::kw_explicit, {FD->getBeginLoc(), FD->getLocation()});
527 if (
auto Err = dropAttributes(TokBuf, FD, DeclarationCleanups))
528 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
531 return std::move(Errors);
532 return getFunctionSourceAfterReplacements(FD, DeclarationCleanups,
536struct InsertionPoint {
537 const DeclContext *EnclosingNamespace =
nullptr;
541enum class RelativeInsertPos { Before, After };
542struct InsertionAnchor {
544 RelativeInsertPos RelInsertPos = RelativeInsertPos::Before;
550SourceRange getDeletionRange(
const FunctionDecl *FD,
551 const syntax::TokenBuffer &TokBuf) {
552 if (!FD->hasBody()) {
553 if (!FD->isExplicitlyDefaulted())
556 auto Tokens = TokBuf.expandedTokens(FD->getSourceRange());
557 for (
auto It = std::rbegin(Tokens); It != std::rend(Tokens); ++It) {
558 if (It->kind() == tok::kw_default) {
559 const auto NextIt = std::next(It);
560 if (NextIt == std::rend(Tokens))
562 const auto &ExpandedEquals = *NextIt;
563 if (ExpandedEquals.kind() != tok::equal)
566 TokBuf.spelledForExpanded(llvm::ArrayRef(ExpandedEquals));
569 return {SpelledEquals->front().location(),
570 FD->getDefaultLoc().getLocWithOffset(1)};
576 auto DeletionRange = FD->getBody()->getSourceRange();
577 if (
auto *CD = llvm::dyn_cast<CXXConstructorDecl>(FD)) {
580 SourceLocation InitStart;
582 for (
const auto *CInit : CD->inits()) {
584 if (CInit->getSourceOrder() != 0)
586 InitStart = CInit->getSourceLocation();
589 if (InitStart.isValid()) {
590 auto Toks = TokBuf.expandedTokens(CD->getSourceRange());
592 Toks = Toks.take_while([&TokBuf, &InitStart](
const syntax::Token &Tok) {
593 return TokBuf.sourceManager().isBeforeInTranslationUnit(Tok.location(),
598 llvm::find_if(llvm::reverse(Toks), [](
const syntax::Token &Tok) {
599 return Tok.kind() == tok::colon;
601 assert(Tok != Toks.rend());
602 DeletionRange.setBegin(Tok->location());
605 return DeletionRange;
624class DefineOutline :
public Tweak {
626 const char *id()
const override;
628 bool hidden()
const override {
return false; }
629 llvm::StringLiteral kind()
const override {
632 std::string title()
const override {
633 if (Source->doesThisDeclarationHaveABody())
634 return "Move function body to out-of-line";
635 return "Create function body out-of-line";
638 bool prepare(
const Selection &Sel)
override {
639 SameFile = !
isHeaderFile(Sel.AST->tuPath(), Sel.AST->getLangOpts());
640 Source = getSelectedFunction(Sel.ASTSelection.commonAncestor());
643 if (!Source || Source->isDeleted() || Source->isOutOfLine())
647 if (!Source->hasBody() && !Source->isExplicitlyDefaulted()) {
649 if (Source->getDefinition())
654 bool HasDefinition =
false;
660 [&HasDefinition](
const Symbol &S) {
662 HasDefinition =
true;
671 if (Source->getTemplateSpecializationInfo())
674 auto *
MD = llvm::dyn_cast<CXXMethodDecl>(Source);
676 if (Source->getDescribedFunctionTemplate())
682 for (
const CXXRecordDecl *Parent =
MD->getParent(); Parent;
684 llvm::dyn_cast_or_null<const CXXRecordDecl>(Parent->getParent())) {
685 if (
const TemplateParameterList *Params =
686 Parent->getDescribedTemplateParams()) {
693 for (NamedDecl *P : *Params) {
694 if (!
P->getIdentifier())
701 if (
MD->getDescribedTemplate())
706 for (
const DeclContext *DC =
MD->getParent(); DC; DC = DC->getParent()) {
707 if (
auto *ND = llvm::dyn_cast<NamedDecl>(DC)) {
708 if (ND->getDeclName().isEmpty() &&
709 (!SameFile || !llvm::dyn_cast<NamespaceDecl>(ND)))
720 Expected<Effect> apply(
const Selection &Sel)
override {
721 const SourceManager &SM = Sel.AST->getSourceManager();
722 std::optional<Path> CCFile;
723 auto Anchor = getDefinitionOfAdjacentDecl(Sel);
725 CCFile = Anchor->Loc.uri.file();
727 CCFile = SameFile ? Sel.AST->tuPath().str()
728 : getSourceFile(Sel.AST->tuPath(), Sel);
731 return error(
"Couldn't find a suitable implementation file.");
732 assert(Sel.FS &&
"FS Must be set in apply");
733 auto Buffer = Sel.FS->getBufferForFile(*CCFile);
737 return llvm::errorCodeToError(Buffer.getError());
739 auto Contents = Buffer->get()->getBuffer();
740 SourceManagerForFile SMFF(*CCFile, Contents);
742 std::optional<Position> InsertionPos;
744 if (
auto P = getInsertionPointFromExistingDefinition(
745 SMFF, **Buffer, Anchor->Loc, Anchor->RelInsertPos, Sel.AST)) {
750 std::optional<std::size_t> Offset;
751 const DeclContext *EnclosingNamespace =
nullptr;
752 std::string EnclosingNamespaceName;
756 Sel.AST->getLangOpts());
757 }
else if (SameFile) {
758 auto P = getInsertionPointInMainFile(Sel.AST);
760 return P.takeError();
762 EnclosingNamespace =
P->EnclosingNamespace;
765 Contents, Source->getQualifiedNameAsString(), Sel.AST->getLangOpts());
766 assert(!Region.EligiblePoints.empty());
767 EnclosingNamespaceName = Region.EnclosingNamespace;
768 InsertionPos = Region.EligiblePoints.back();
774 return O.takeError();
777 findContextForNS(EnclosingNamespaceName, Source->getDeclContext());
779 return error(
"define outline: couldn't find a context for target");
780 EnclosingNamespace = *TargetContext;
784 assert(EnclosingNamespace);
786 auto FuncDef = getFunctionSourceCode(
787 Source, EnclosingNamespace, Sel.AST->getTokens(),
788 Sel.AST->getHeuristicResolver(),
789 SameFile &&
isHeaderFile(Sel.AST->tuPath(), Sel.AST->getLangOpts()));
791 return FuncDef.takeError();
793 const tooling::Replacement InsertFunctionDef(*CCFile, *Offset, 0, *FuncDef);
794 auto Effect = Effect::mainFileEdit(
795 SMFF.get(), tooling::Replacements(InsertFunctionDef));
797 return Effect.takeError();
799 tooling::Replacements HeaderUpdates;
800 auto DeletionRange = getDeletionRange(Source, Sel.AST->getTokens());
801 if (DeletionRange.isValid()) {
802 if (
auto Error = HeaderUpdates.add(tooling::Replacement(
803 Sel.AST->getSourceManager(),
805 SM, Sel.AST->getLangOpts(), DeletionRange)),
811 if (Source->isInlineSpecified()) {
813 deleteTokensWithKind(Sel.AST->getTokens(), tok::kw_inline,
814 {Source->getBeginLoc(), Source->getLocation()});
816 return DelInline.takeError();
817 HeaderUpdates = HeaderUpdates.merge(*DelInline);
821 tooling::Replacements &R = Effect->ApplyEdits[*CCFile].Replacements;
822 R = R.merge(HeaderUpdates);
824 auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
826 return HeaderFE.takeError();
827 Effect->ApplyEdits.try_emplace(HeaderFE->first,
828 std::move(HeaderFE->second));
830 return std::move(*Effect);
833 std::optional<InsertionAnchor>
834 getDefinitionOfAdjacentDecl(
const Selection &Sel) {
837 std::optional<Location> Anchor;
839 auto CheckCandidate = [&](Decl *Candidate) {
840 assert(Candidate != Source);
841 if (
auto Func = llvm::dyn_cast_or_null<FunctionDecl>(Candidate);
842 !Func || Func->isThisDeclarationADefinition()) {
845 std::optional<Location> CandidateLoc;
846 Sel.Index->lookup({{
getSymbolID(Candidate)}}, [&](
const Symbol &S) {
851 log(
"getDefinitionOfAdjacentDecl: {0}", Loc.takeError());
865 bool CandidateSameFile = TuURI == CandidateLoc->uri.uri();
866 if (SameFile && !CandidateSameFile)
868 if (!SameFile && CandidateSameFile) {
869 if (Candidate->isTemplateDecl())
873 Anchor = *CandidateLoc;
879 const DeclContext *ParentContext = Source->getParent();
880 const auto SourceIt = llvm::find_if(
881 ParentContext->decls(), [
this](
const Decl *D) { return D == Source; });
882 if (SourceIt == ParentContext->decls_end())
884 const int Preceding = std::distance(ParentContext->decls_begin(), SourceIt);
885 const int Following =
886 std::distance(SourceIt, ParentContext->decls_end()) - 1;
887 for (
int Offset = 1; Offset <= Preceding || Offset <= Following; ++Offset) {
888 if (Offset <= Preceding)
890 *std::next(ParentContext->decls_begin(), Preceding - Offset));
892 return InsertionAnchor{*Anchor, RelativeInsertPos::After};
893 if (Offset <= Following)
894 CheckCandidate(*std::next(SourceIt, Offset));
896 return InsertionAnchor{*Anchor, RelativeInsertPos::Before};
904 std::optional<Position> getInsertionPointFromExistingDefinition(
905 SourceManagerForFile &SMFF,
const llvm::MemoryBuffer &Buffer,
906 const Location &Loc, RelativeInsertPos RelInsertPos, ParsedAST *
AST) {
910 SourceLocation InsertionLoc;
911 SourceManager &SM = SMFF.get();
913 auto InsertBefore = [&] {
920 auto Tokens = syntax::tokenize(
921 syntax::FileRange(SM.getMainFileID(), 0, *StartOffset), SM,
925 for (
auto I = std::rbegin(Tokens);
926 InsertionLoc.isInvalid() && I != std::rend(Tokens); ++I) {
931 if (I != std::rbegin(Tokens))
932 InsertionLoc = std::prev(I)->location();
934 InsertionLoc = I->endLocation();
940 if (InsertionLoc.isInvalid())
941 InsertionLoc = Tokens.front().location();
944 if (RelInsertPos == RelativeInsertPos::Before) {
951 syntax::tokenize(syntax::FileRange(SM.getMainFileID(), *StartOffset,
952 Buffer.getBuffer().size()),
953 SM,
AST->getLangOpts());
954 std::optional<syntax::Token> Tok;
957 auto ClosingParen = skipTokenPair(Tokens.begin(), Tokens.end(),
958 tok::l_paren, tok::r_paren);
959 if (ClosingParen != Tokens.end()) {
961 auto AfterParams = std::next(ClosingParen);
962 if (AfterParams != Tokens.end() && AfterParams->kind() == tok::equal) {
963 auto NextIt = std::next(AfterParams);
964 if (NextIt != Tokens.end() && NextIt->kind() == tok::kw_default) {
966 auto SemiIt = std::next(NextIt);
967 if (SemiIt != Tokens.end() && SemiIt->kind() == tok::semi) {
974 if (!Tok && AfterParams != Tokens.end()) {
975 auto ClosingBrace = skipTokenPair(AfterParams, Tokens.end(),
976 tok::l_brace, tok::r_brace);
977 if (ClosingBrace != Tokens.end()) {
984 InsertionLoc = Tok->endLocation();
989 if (!InsertionLoc.isValid())
997 llvm::Expected<InsertionPoint> getInsertionPointInMainFile(ParsedAST *
AST) {
1001 auto *Klass = Source->getDeclContext()->getOuterLexicalRecordContext();
1003 return error(
"moving to same file not supported for free functions");
1004 const SourceLocation EndLoc = Klass->getBraceRange().getEnd();
1005 const auto &TokBuf =
AST->getTokens();
1006 auto Tokens = TokBuf.expandedTokens();
1007 auto It = llvm::lower_bound(
1008 Tokens, EndLoc, [](
const syntax::Token &Tok, SourceLocation EndLoc) {
1009 return Tok.location() < EndLoc;
1011 while (It != Tokens.end()) {
1012 if (It->kind() != tok::semi) {
1017 AST->getSourceManager().getDecomposedLoc(It->endLocation()).second;
1018 return InsertionPoint{Klass->getEnclosingNamespaceContext(), Offset};
1021 "failed to determine insertion location: no end of class found");
1025 const FunctionDecl *Source =
nullptr;
1026 bool SameFile =
false;
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for Markdown output.")
#define REGISTER_TWEAK(Subclass)
An interface base for small context-sensitive refactoring actions.
static URI createFile(llvm::StringRef AbsolutePath)
This creates a file:// URI for AbsolutePath. The path must be absolute.
std::string toString() const
Returns a string URI with all components percent-encoded.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
llvm::Expected< Location > indexToLSPLocation(const SymbolLocation &Loc, llvm::StringRef TUPath)
Helper function for deriving an LSP Location from an index SymbolLocation.
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
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)
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
void log(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.
std::string getNamespaceAtPosition(StringRef Code, const Position &Pos, const LangOptions &LangOpts)
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
void elog(const char *Fmt, Ts &&... Vals)
bool isHeaderFile(llvm::StringRef FileName, std::optional< LangOptions > LangOpts)
Infers whether this is a header from the FileName and LangOpts (if presents).
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Simplified description of a clang AST node.
static const llvm::StringLiteral REFACTOR_KIND
Represents a symbol occurrence in the source file.
Information about a reference written in the source code, independent of the actual AST node that thi...
Input to prepare and apply tweaks.