clang-tools 24.0.0git
DefineOutline.cpp
Go to the documentation of this file.
1//===--- DefineOutline.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-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "AST.h"
10#include "FindSymbols.h"
11#include "FindTarget.h"
12#include "HeaderSourceSwitch.h"
13#include "ParsedAST.h"
14#include "Selection.h"
15#include "SourceCode.h"
16#include "refactor/Tweak.h"
17#include "support/Logger.h"
18#include "support/Path.h"
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"
37#include <cstddef>
38#include <iterator>
39#include <optional>
40#include <string>
41
42namespace clang {
43namespace clangd {
44namespace {
45
46// Deduces the FunctionDecl from a selection. Requires either the function body
47// or the function decl to be selected. Returns null if none of the above
48// criteria is met.
49// FIXME: This is shared with define inline, move them to a common header once
50// we have a place for such.
51const FunctionDecl *getSelectedFunction(const SelectionTree::Node *SelNode) {
52 if (!SelNode)
53 return nullptr;
54 const DynTypedNode &AstNode = SelNode->ASTNode;
55 if (const FunctionDecl *FD = AstNode.get<FunctionDecl>())
56 return FD;
57 if (AstNode.get<CompoundStmt>() &&
58 SelNode->Selected == SelectionTree::Complete) {
59 if (const SelectionTree::Node *P = SelNode->Parent)
60 return P->ASTNode.get<FunctionDecl>();
61 }
62 return nullptr;
63}
64
65std::optional<Path> getSourceFile(llvm::StringRef FileName,
66 const Tweak::Selection &Sel) {
67 assert(Sel.FS);
68 if (auto Source = getCorrespondingHeaderOrSource(FileName, Sel.FS))
69 return *Source;
70 return getCorrespondingHeaderOrSource(FileName, *Sel.AST, Sel.Index);
71}
72
73// Synthesize a DeclContext for TargetNS from CurContext. TargetNS must be empty
74// for global namespace, and endwith "::" otherwise.
75// Returns std::nullopt if TargetNS is not a prefix of CurContext.
76std::optional<const DeclContext *>
77findContextForNS(llvm::StringRef TargetNS, const DeclContext *CurContext) {
78 assert(TargetNS.empty() || TargetNS.ends_with("::"));
79 // Skip any non-namespace contexts, e.g. TagDecls, functions/methods.
80 CurContext = CurContext->getEnclosingNamespaceContext();
81 // If TargetNS is empty, it means global ns, which is translation unit.
82 if (TargetNS.empty()) {
83 while (!CurContext->isTranslationUnit())
84 CurContext = CurContext->getParent();
85 return CurContext;
86 }
87 // Otherwise we need to drop any trailing namespaces from CurContext until
88 // we reach TargetNS.
89 std::string TargetContextNS =
90 CurContext->isNamespace()
91 ? llvm::cast<NamespaceDecl>(CurContext)->getQualifiedNameAsString()
92 : "";
93 TargetContextNS.append("::");
94
95 llvm::StringRef CurrentContextNS(TargetContextNS);
96 // If TargetNS is not a prefix of CurrentContext, there's no way to reach
97 // it.
98 if (!CurrentContextNS.starts_with(TargetNS))
99 return std::nullopt;
100
101 while (CurrentContextNS != TargetNS) {
102 CurContext = CurContext->getParent();
103 // These colons always exists since TargetNS is a prefix of
104 // CurrentContextNS, it ends with "::" and they are not equal.
105 CurrentContextNS = CurrentContextNS.take_front(
106 CurrentContextNS.drop_back(2).rfind("::") + 2);
107 }
108 return CurContext;
109}
110
111// Returns source code for FD after applying Replacements.
112// FIXME: Make the function take a parameter to return only the function body,
113// afterwards it can be shared with define-inline code action.
114llvm::Expected<std::string>
115getFunctionSourceAfterReplacements(const FunctionDecl *FD,
116 const tooling::Replacements &Replacements,
117 bool TargetFileIsHeader) {
118 const auto &SM = FD->getASTContext().getSourceManager();
119 auto OrigFuncRange = toHalfOpenFileRange(
120 SM, FD->getASTContext().getLangOpts(), FD->getSourceRange());
121 if (!OrigFuncRange)
122 return error("Couldn't get range for function.");
123
124 // Get new begin and end positions for the qualified function definition.
125 unsigned FuncBegin = SM.getFileOffset(OrigFuncRange->getBegin());
126 unsigned FuncEnd = Replacements.getShiftedCodePosition(
127 SM.getFileOffset(OrigFuncRange->getEnd()));
128
129 // Trim the result to function definition.
130 auto QualifiedFunc = tooling::applyAllReplacements(
131 SM.getBufferData(SM.getMainFileID()), Replacements);
132 if (!QualifiedFunc)
133 return QualifiedFunc.takeError();
134
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();
139 if (!Params)
140 return;
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();
148 }
149 std::string S;
150 llvm::raw_string_ostream Stream(S);
151 Params->print(Stream, FD->getASTContext());
152 if (!S.empty())
153 *S.rbegin() = '\n'; // Replace space with newline
154 TemplatePrefix.insert(0, S);
155 };
156 AddToTemplatePrefixIfApplicable(FD);
157 if (auto *MD = llvm::dyn_cast<CXXMethodDecl>(FD)) {
158 for (const CXXRecordDecl *Parent = MD->getParent(); Parent;
159 Parent =
160 llvm::dyn_cast_or_null<const CXXRecordDecl>(Parent->getParent())) {
161 AddToTemplatePrefixIfApplicable(Parent);
162 }
163 }
164
165 if (TargetFileIsHeader)
166 Source.insert(0, "inline ");
167 if (!TemplatePrefix.empty())
168 Source.insert(0, TemplatePrefix);
169 if (!FD->hasBody() && !FD->isExplicitlyDefaulted()) {
170 Source.pop_back(); // The semicolon finishing the declaration.
171 Source += " {";
172 if (!FD->getReturnType()->isVoidType())
173 Source += " return {}; ";
174 Source += "}";
175 }
176
177 return Source;
178}
179
180// Returns replacements to delete tokens with kind `Kind` in the range
181// `FromRange`. Removes matching instances of given token preceeding the
182// function defition.
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)
191 continue;
192 FoundAny = true;
193 auto Spelling = TokBuf.spelledForExpanded(llvm::ArrayRef(Tok));
194 if (!Spelling) {
195 Errors = llvm::joinErrors(
196 std::move(Errors),
197 error("define outline: couldn't remove `{0}` keyword.",
198 tok::getKeywordSpelling(Kind)));
199 break;
200 }
201 auto &SM = TokBuf.sourceManager();
202 CharSourceRange DelRange =
203 syntax::Token::range(SM, Spelling->front(), Spelling->back())
204 .toCharRange(SM);
205 if (auto Err =
206 DelKeywordCleanups.add(tooling::Replacement(SM, DelRange, "")))
207 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
208 }
209 if (!FoundAny) {
210 Errors = llvm::joinErrors(
211 std::move(Errors),
212 error("define outline: couldn't find `{0}` keyword to remove.",
213 tok::getKeywordSpelling(Kind)));
214 }
215
216 if (Errors)
217 return std::move(Errors);
218 return DelKeywordCleanups;
219}
220
221// Helper function to skip over a matching pair of tokens (e.g., parentheses
222// or braces). Returns an iterator to the matching closing token, or the end
223// iterator if no matching pair is found.
224template <typename Iterator>
225Iterator skipTokenPair(Iterator Begin, Iterator End, tok::TokenKind StartKind,
226 tok::TokenKind EndKind) {
227 int Count = 0;
228 for (auto It = Begin; It != End; ++It) {
229 if (It->kind() == StartKind) {
230 ++Count;
231 } else if (It->kind() == EndKind) {
232 if (--Count == 0)
233 return It;
234 if (Count < 0)
235 // We encountered a closing token without a matching opening token.
236 return End;
237 }
238 }
239 return End;
240}
241
242// Delete the attributes that should not appear in the generated function
243// definition. Some attributes must be repeated on the definition. If the
244// function has one of those, we leave all attributes alone.
245llvm::Error dropAttributes(const syntax::TokenBuffer &TokBuf,
246 const FunctionDecl *FD,
247 tooling::Replacements &DeclarationCleanups) {
248 llvm::Error Errors = llvm::Error::success();
249 if (!FD->hasAttrs())
250 return Errors;
251
252 // Some attributes are part of a function's identity and must be repeated on
253 // the definition so that it still matches the declaration: attributes that
254 // make a function multiversioned (e.g. target, cpu_specific) and attributes
255 // like enable_if and overloadable. Leave all attributes alone in this case.
256 if (FD->isMultiVersion() || FD->hasAttr<EnableIfAttr>() ||
257 FD->hasAttr<OverloadableAttr>()) {
258 return Errors;
259 }
260
261 for (const Attr *A : FD->attrs()) {
262 // Non-inheritable attributes are not inherited by the definition. As one
263 // may share an attribute list with an inheritable attribute, which we would
264 // delete along with the list, we better don't drop anything in this case.
265 if (A->isImplicit() || A->isInherited())
266 continue;
267 if (!isa<InheritableAttr>(A))
268 return Errors;
269 }
270
271 const SourceManager &SM = TokBuf.sourceManager();
272
273 // Do nothing if the function has no body.
274 const Stmt *Body = FD->getBody();
275 if (!Body)
276 return Errors;
277
278 auto FDTokens = TokBuf.spelledForExpanded(
279 TokBuf.expandedTokens({FD->getBeginLoc(), Body->getBeginLoc()}));
280
281 // Drop attributes that the out-of-line definition inherits from the
282 // declaration. Ones we can't safely locate are left alone.
283 // FIXME: Attributes coming from macros and attributes unknown to clang (which
284 // are not part of the AST) are not dropped.
285 for (const Attr *A : FD->attrs()) {
286 // Get the delimiter for the attribute type
287 llvm::SmallVector<tok::TokenKind> LeftDelimiter, RightDelimiter;
288 switch (A->getSyntax()) {
289 case AttributeCommonInfo::AS_GNU:
290 // Delimited by __attribute__(( and ))
291 LeftDelimiter.assign({tok::kw___attribute, tok::l_paren, tok::l_paren});
292 RightDelimiter.assign({tok::r_paren, tok::r_paren});
293 break;
294 case AttributeCommonInfo::AS_CXX11:
295 case AttributeCommonInfo::AS_C23:
296 // Delimited by [[ and ]]
297 LeftDelimiter.assign({tok::l_square, tok::l_square});
298 RightDelimiter.assign({tok::r_square, tok::r_square});
299 break;
300 case AttributeCommonInfo::AS_Declspec:
301 // Delimited by __declspec( and )
302 LeftDelimiter.assign({tok::kw___declspec, tok::l_paren});
303 RightDelimiter.assign({tok::r_paren});
304 break;
305 default:
306 // Keyword (e.g. __forceinline) and Microsoft ([...]) attributes are not
307 // handled, they are still copied to the definition.
308 break;
309 }
310
311 if (LeftDelimiter.empty() || RightDelimiter.empty())
312 continue;
313
314 auto AttrTokens =
315 TokBuf.spelledForExpanded(TokBuf.expandedTokens(A->getRange()));
316
317 if (!FDTokens.has_value() || !AttrTokens.has_value() ||
318 !SM.isPointWithin(A->getLocation(), FDTokens->front().location(),
319 FDTokens->back().location()))
320 continue;
321
322 CharSourceRange DelRange;
323
324 // Find position of the right delimiter
325 for (auto It = AttrTokens->end(), E = FDTokens->end(); It != E; ++It) {
326 // There might be a further attribute with argument delimited by parens
327 // in the attribute list. The closing paren might be recognized as part
328 // of the attribute delimiter. So skip tokens until the closing paren.
329 if (It->kind() == tok::l_paren) {
330 It = skipTokenPair(It, E, tok::l_paren, tok::r_paren);
331 if (It != E)
332 continue;
333 }
334
335 if (std::distance(It, E) < static_cast<long>(RightDelimiter.size()))
336 // No chance to find the right delimiter. Give up.
337 break;
338
339 llvm::ArrayRef<syntax::Token> Candidate(It, RightDelimiter.size());
340
341 if (llvm::equal(Candidate, RightDelimiter,
342 [](const auto &Tok, const auto &TokKindDel) {
343 return Tok.kind() == TokKindDel;
344 })) {
345 DelRange.setEnd(Candidate.back().endLocation());
346 break;
347 }
348 }
349
350 // Find position of the left delimiter
351 for (auto It = AttrTokens->begin(), E = FDTokens->begin(); It != E; --It) {
352 if (std::distance(E, It) < static_cast<long>(LeftDelimiter.size()))
353 break;
354
355 llvm::ArrayRef<syntax::Token> Candidate(
356 std::prev(It, LeftDelimiter.size()), LeftDelimiter.size());
357
358 if (llvm::equal(Candidate, LeftDelimiter,
359 [](const auto &Tok, const auto &TokKindDel) {
360 return Tok.kind() == TokKindDel;
361 })) {
362 DelRange.setBegin(Candidate.front().location());
363 break;
364 }
365 }
366
367 if (DelRange.isValid()) {
368 if (auto Err =
369 DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
370 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
371 }
372 }
373 return Errors;
374}
375
376// Creates a modified version of function definition that can be inserted at a
377// different location, qualifies return value and function name to achieve that.
378// Contains function signature, except defaulted parameter arguments, body and
379// template parameters if applicable. No need to qualify parameters, as they are
380// looked up in the context containing the function/method.
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();
388
389 llvm::Error Errors = llvm::Error::success();
390 tooling::Replacements DeclarationCleanups;
391
392 // Finds the first unqualified name in function return type and name, then
393 // qualifies those to be valid in TargetContext.
395 FD,
396 [&](ReferenceLoc Ref) {
397 // It is enough to qualify the first qualifier, so skip references with
398 // a qualifier. Also we can't do much if there are no targets or name is
399 // inside a macro body.
400 if (Ref.Qualifier || Ref.Targets.empty() || Ref.NameLoc.isMacroID())
401 return;
402 // Only qualify return type and function name.
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(),
409 Ref.NameLoc)))
410 return;
411
412 for (const NamedDecl *ND : Ref.Targets) {
413 if (ND->getKind() == Decl::TemplateTypeParm)
414 return;
415 if (ND->getDeclContext() != Ref.Targets.front()->getDeclContext()) {
416 elog("Targets from multiple contexts: {0}, {1}",
417 printQualifiedName(*Ref.Targets.front()),
418 printQualifiedName(*ND));
419 return;
420 }
421 }
422 const NamedDecl *ND = Ref.Targets.front();
423 std::string Qualifier =
424 getQualification(AST, TargetContext,
425 SM.getLocForStartOfFile(SM.getMainFileID()), ND);
426 if (ND->getDeclContext()->isDependentContext() &&
427 llvm::isa<TypeDecl>(ND)) {
428 Qualifier.insert(0, "typename ");
429 }
430 if (auto Err = DeclarationCleanups.add(
431 tooling::Replacement(SM, Ref.NameLoc, 0, Qualifier)))
432 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
433 },
434 Resolver);
435
436 // findExplicitReferences doesn't provide references to
437 // constructor/destructors, it only provides references to type names inside
438 // them.
439 // this works for constructors, but doesn't work for destructor as type name
440 // doesn't cover leading `~`, so handle it specially.
441 if (const auto *Destructor = llvm::dyn_cast<CXXDestructorDecl>(FD)) {
442 if (auto Err = DeclarationCleanups.add(tooling::Replacement(
443 SM, Destructor->getLocation(), 0,
444 getQualification(AST, TargetContext,
445 SM.getLocForStartOfFile(SM.getMainFileID()),
446 Destructor))))
447 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
448 }
449
450 // Get rid of default arguments, since they should not be specified in
451 // out-of-line definition.
452 for (const auto *PVD : FD->parameters()) {
453 if (!PVD->hasDefaultArg())
454 continue;
455 // Deletion range spans the initializer, usually excluding the `=`.
456 auto DelRange = CharSourceRange::getTokenRange(PVD->getDefaultArgRange());
457 // Get all tokens before the default argument.
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());
462 });
463 if (TokBuf.expandedTokens(DelRange.getAsRange()).front().kind() !=
464 tok::equal) {
465 // Find the last `=` if it isn't included in the initializer, and update
466 // the DelRange to include it.
467 auto Tok =
468 llvm::find_if(llvm::reverse(Tokens), [](const syntax::Token &Tok) {
469 return Tok.kind() == tok::equal;
470 });
471 assert(Tok != Tokens.rend());
472 DelRange.setBegin(Tok->location());
473 }
474 if (auto Err =
475 DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
476 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
477 }
478
479 auto DelAttr = [&](const Attr *A) {
480 if (!A)
481 return;
482 auto AttrTokens =
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.",
489 A->getSpelling()));
490 return;
491 }
492 CharSourceRange DelRange =
493 syntax::Token::range(SM, AttrTokens->front(), AttrTokens->back())
494 .toCharRange(SM);
495 if (auto Err =
496 DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
497 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
498 };
499
500 DelAttr(FD->getAttr<OverrideAttr>());
501 DelAttr(FD->getAttr<FinalAttr>());
502
503 auto DelKeyword = [&](tok::TokenKind Kind, SourceRange FromRange) {
504 auto DelKeywords = deleteTokensWithKind(TokBuf, Kind, FromRange);
505 if (!DelKeywords) {
506 Errors = llvm::joinErrors(std::move(Errors), DelKeywords.takeError());
507 return;
508 }
509 DeclarationCleanups = DeclarationCleanups.merge(*DelKeywords);
510 };
511
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()});
517 if (MD->isStatic())
518 DelKeyword(tok::kw_static, {FD->getBeginLoc(), FD->getLocation()});
519 }
520 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
521 if (CD->isExplicit())
522 DelKeyword(tok::kw_explicit, {FD->getBeginLoc(), FD->getLocation()});
523 }
524
525 // Must come after the keyword deletions above, otherwise keywords such as
526 // `static` are no longer removed (their offsets are shifted by merge()).
527 if (auto Err = dropAttributes(TokBuf, FD, DeclarationCleanups))
528 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
529
530 if (Errors)
531 return std::move(Errors);
532 return getFunctionSourceAfterReplacements(FD, DeclarationCleanups,
533 TargetFileIsHeader);
534}
535
536struct InsertionPoint {
537 const DeclContext *EnclosingNamespace = nullptr;
538 size_t Offset;
539};
540
541enum class RelativeInsertPos { Before, After };
542struct InsertionAnchor {
543 Location Loc;
544 RelativeInsertPos RelInsertPos = RelativeInsertPos::Before;
545};
546
547// Returns the range that should be deleted from declaration, which always
548// contains function body. In addition to that it might contain constructor
549// initializers.
550SourceRange getDeletionRange(const FunctionDecl *FD,
551 const syntax::TokenBuffer &TokBuf) {
552 if (!FD->hasBody()) {
553 if (!FD->isExplicitlyDefaulted())
554 return {};
555
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))
561 return {};
562 const auto &ExpandedEquals = *NextIt;
563 if (ExpandedEquals.kind() != tok::equal)
564 return {};
565 auto SpelledEquals =
566 TokBuf.spelledForExpanded(llvm::ArrayRef(ExpandedEquals));
567 if (!SpelledEquals)
568 return {};
569 return {SpelledEquals->front().location(),
570 FD->getDefaultLoc().getLocWithOffset(1)};
571 }
572 }
573 return {};
574 }
575
576 auto DeletionRange = FD->getBody()->getSourceRange();
577 if (auto *CD = llvm::dyn_cast<CXXConstructorDecl>(FD)) {
578 // AST doesn't contain the location for ":" in ctor initializers. Therefore
579 // we find it by finding the first ":" before the first ctor initializer.
580 SourceLocation InitStart;
581 // Find the first initializer.
582 for (const auto *CInit : CD->inits()) {
583 // SourceOrder is -1 for implicit initializers.
584 if (CInit->getSourceOrder() != 0)
585 continue;
586 InitStart = CInit->getSourceLocation();
587 break;
588 }
589 if (InitStart.isValid()) {
590 auto Toks = TokBuf.expandedTokens(CD->getSourceRange());
591 // Drop any tokens after the initializer.
592 Toks = Toks.take_while([&TokBuf, &InitStart](const syntax::Token &Tok) {
593 return TokBuf.sourceManager().isBeforeInTranslationUnit(Tok.location(),
594 InitStart);
595 });
596 // Look for the first colon.
597 auto Tok =
598 llvm::find_if(llvm::reverse(Toks), [](const syntax::Token &Tok) {
599 return Tok.kind() == tok::colon;
600 });
601 assert(Tok != Toks.rend());
602 DeletionRange.setBegin(Tok->location());
603 }
604 }
605 return DeletionRange;
606}
607
608/// Moves definition of a function/method to an appropriate implementation file.
609///
610/// Before:
611/// a.h
612/// void foo() { return; }
613/// a.cc
614/// #include "a.h"
615///
616/// ----------------
617///
618/// After:
619/// a.h
620/// void foo();
621/// a.cc
622/// #include "a.h"
623/// void foo() { return; }
624class DefineOutline : public Tweak {
625public:
626 const char *id() const override;
627
628 bool hidden() const override { return false; }
629 llvm::StringLiteral kind() const override {
631 }
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";
636 }
637
638 bool prepare(const Selection &Sel) override {
639 SameFile = !isHeaderFile(Sel.AST->tuPath(), Sel.AST->getLangOpts());
640 Source = getSelectedFunction(Sel.ASTSelection.commonAncestor());
641
642 // Bail out if the selection is not a function declaration.
643 if (!Source || Source->isDeleted() || Source->isOutOfLine())
644 return false;
645
646 // Bail out if a definition exists somewhere else.
647 if (!Source->hasBody() && !Source->isExplicitlyDefaulted()) {
648 // Check AST first.
649 if (Source->getDefinition())
650 return false;
651
652 // Then consult the index.
653 if (Sel.Index) {
654 bool HasDefinition = false;
655
656 // Note: Once other code actions want to start querying the index for
657 // the symbol under the cursor in their prepare() function, this look-up
658 // should get consolidated in some manner (e.g. a cache).
659 Sel.Index->lookup({{getSymbolID(Source)}},
660 [&HasDefinition](const Symbol &S) {
661 if (S.Definition)
662 HasDefinition = true;
663 });
664 if (HasDefinition)
665 return false;
666 }
667 }
668
669 // Bail out if this is a function template or specialization, as their
670 // definitions need to be visible in all including translation units.
671 if (Source->getTemplateSpecializationInfo())
672 return false;
673
674 auto *MD = llvm::dyn_cast<CXXMethodDecl>(Source);
675 if (!MD) {
676 if (Source->getDescribedFunctionTemplate())
677 return false;
678 // Can't outline free-standing functions in the same file.
679 return !SameFile;
680 }
681
682 for (const CXXRecordDecl *Parent = MD->getParent(); Parent;
683 Parent =
684 llvm::dyn_cast_or_null<const CXXRecordDecl>(Parent->getParent())) {
685 if (const TemplateParameterList *Params =
686 Parent->getDescribedTemplateParams()) {
687
688 // Class template member functions must be defined in the
689 // same file.
690 SameFile = true;
691
692 // Bail out if the template parameter is unnamed.
693 for (NamedDecl *P : *Params) {
694 if (!P->getIdentifier())
695 return false;
696 }
697 }
698 }
699
700 // Function templates must be defined in the same file.
701 if (MD->getDescribedTemplate())
702 SameFile = true;
703
704 // The refactoring is meaningless for unnamed classes and namespaces,
705 // unless we're outlining in the same file
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)))
710 return false;
711 }
712 }
713
714 // Note that we don't check whether an implementation file exists or not in
715 // the prepare, since performing disk IO on each prepare request might be
716 // expensive.
717 return true;
718 }
719
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);
724 if (Anchor) {
725 CCFile = Anchor->Loc.uri.file();
726 } else {
727 CCFile = SameFile ? Sel.AST->tuPath().str()
728 : getSourceFile(Sel.AST->tuPath(), Sel);
729 }
730 if (!CCFile)
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);
734 // FIXME: Maybe we should consider creating the implementation file if it
735 // doesn't exist?
736 if (!Buffer)
737 return llvm::errorCodeToError(Buffer.getError());
738
739 auto Contents = Buffer->get()->getBuffer();
740 SourceManagerForFile SMFF(*CCFile, Contents);
741
742 std::optional<Position> InsertionPos;
743 if (Anchor) {
744 if (auto P = getInsertionPointFromExistingDefinition(
745 SMFF, **Buffer, Anchor->Loc, Anchor->RelInsertPos, Sel.AST)) {
746 InsertionPos = *P;
747 }
748 }
749
750 std::optional<std::size_t> Offset;
751 const DeclContext *EnclosingNamespace = nullptr;
752 std::string EnclosingNamespaceName;
753
754 if (InsertionPos) {
755 EnclosingNamespaceName = getNamespaceAtPosition(Contents, *InsertionPos,
756 Sel.AST->getLangOpts());
757 } else if (SameFile) {
758 auto P = getInsertionPointInMainFile(Sel.AST);
759 if (!P)
760 return P.takeError();
761 Offset = P->Offset;
762 EnclosingNamespace = P->EnclosingNamespace;
763 } else {
764 auto Region = getEligiblePoints(
765 Contents, Source->getQualifiedNameAsString(), Sel.AST->getLangOpts());
766 assert(!Region.EligiblePoints.empty());
767 EnclosingNamespaceName = Region.EnclosingNamespace;
768 InsertionPos = Region.EligiblePoints.back();
769 }
770
771 if (InsertionPos) {
772 auto O = positionToOffset(Contents, *InsertionPos);
773 if (!O)
774 return O.takeError();
775 Offset = *O;
776 auto TargetContext =
777 findContextForNS(EnclosingNamespaceName, Source->getDeclContext());
778 if (!TargetContext)
779 return error("define outline: couldn't find a context for target");
780 EnclosingNamespace = *TargetContext;
781 }
782
783 assert(Offset);
784 assert(EnclosingNamespace);
785
786 auto FuncDef = getFunctionSourceCode(
787 Source, EnclosingNamespace, Sel.AST->getTokens(),
788 Sel.AST->getHeuristicResolver(),
789 SameFile && isHeaderFile(Sel.AST->tuPath(), Sel.AST->getLangOpts()));
790 if (!FuncDef)
791 return FuncDef.takeError();
792
793 const tooling::Replacement InsertFunctionDef(*CCFile, *Offset, 0, *FuncDef);
794 auto Effect = Effect::mainFileEdit(
795 SMFF.get(), tooling::Replacements(InsertFunctionDef));
796 if (!Effect)
797 return Effect.takeError();
798
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(),
804 CharSourceRange::getTokenRange(*toHalfOpenFileRange(
805 SM, Sel.AST->getLangOpts(), DeletionRange)),
806 ";"))) {
807 return Error;
808 }
809 }
810
811 if (Source->isInlineSpecified()) {
812 auto DelInline =
813 deleteTokensWithKind(Sel.AST->getTokens(), tok::kw_inline,
814 {Source->getBeginLoc(), Source->getLocation()});
815 if (!DelInline)
816 return DelInline.takeError();
817 HeaderUpdates = HeaderUpdates.merge(*DelInline);
818 }
819
820 if (SameFile) {
821 tooling::Replacements &R = Effect->ApplyEdits[*CCFile].Replacements;
822 R = R.merge(HeaderUpdates);
823 } else {
824 auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
825 if (!HeaderFE)
826 return HeaderFE.takeError();
827 Effect->ApplyEdits.try_emplace(HeaderFE->first,
828 std::move(HeaderFE->second));
829 }
830 return std::move(*Effect);
831 }
832
833 std::optional<InsertionAnchor>
834 getDefinitionOfAdjacentDecl(const Selection &Sel) {
835 if (!Sel.Index)
836 return {};
837 std::optional<Location> Anchor;
838 std::string TuURI = URI::createFile(Sel.AST->tuPath()).toString();
839 auto CheckCandidate = [&](Decl *Candidate) {
840 assert(Candidate != Source);
841 if (auto Func = llvm::dyn_cast_or_null<FunctionDecl>(Candidate);
842 !Func || Func->isThisDeclarationADefinition()) {
843 return;
844 }
845 std::optional<Location> CandidateLoc;
846 Sel.Index->lookup({{getSymbolID(Candidate)}}, [&](const Symbol &S) {
847 if (S.Definition) {
848 if (auto Loc = indexToLSPLocation(S.Definition, Sel.AST->tuPath()))
849 CandidateLoc = *Loc;
850 else
851 log("getDefinitionOfAdjacentDecl: {0}", Loc.takeError());
852 }
853 });
854 if (!CandidateLoc)
855 return;
856
857 // If our definition is constrained to the same file, ignore
858 // definitions that are not located there.
859 // If our definition is not constrained to the same file, but
860 // our anchor definition is in the same file, then we also put our
861 // definition there, because that appears to be the user preference.
862 // Exception: If the existing definition is a template, then the
863 // location is likely due to technical necessity rather than preference,
864 // so ignore that definition.
865 bool CandidateSameFile = TuURI == CandidateLoc->uri.uri();
866 if (SameFile && !CandidateSameFile)
867 return;
868 if (!SameFile && CandidateSameFile) {
869 if (Candidate->isTemplateDecl())
870 return;
871 SameFile = true;
872 }
873 Anchor = *CandidateLoc;
874 };
875
876 // Try to find adjacent function declarations.
877 // Determine the closest one by alternatingly going "up" and "down"
878 // from our function in increasing steps.
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())
883 return {};
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)
889 CheckCandidate(
890 *std::next(ParentContext->decls_begin(), Preceding - Offset));
891 if (Anchor)
892 return InsertionAnchor{*Anchor, RelativeInsertPos::After};
893 if (Offset <= Following)
894 CheckCandidate(*std::next(SourceIt, Offset));
895 if (Anchor)
896 return InsertionAnchor{*Anchor, RelativeInsertPos::Before};
897 }
898 return {};
899 }
900
901 // We don't know the actual start or end of the definition, only the position
902 // of the name. Therefore, we heuristically try to locate the last token
903 // before or in this function, respectively. Adapt as required by user code.
904 std::optional<Position> getInsertionPointFromExistingDefinition(
905 SourceManagerForFile &SMFF, const llvm::MemoryBuffer &Buffer,
906 const Location &Loc, RelativeInsertPos RelInsertPos, ParsedAST *AST) {
907 auto StartOffset = positionToOffset(Buffer.getBuffer(), Loc.range.start);
908 if (!StartOffset)
909 return {};
910 SourceLocation InsertionLoc;
911 SourceManager &SM = SMFF.get();
912
913 auto InsertBefore = [&] {
914 // Go backwards until we encounter one of the following:
915 // - An opening brace (of a namespace).
916 // - A closing brace (of a function definition).
917 // - A semicolon (of a declaration).
918 // If no such token was found, then the first token in the file starts the
919 // definition.
920 auto Tokens = syntax::tokenize(
921 syntax::FileRange(SM.getMainFileID(), 0, *StartOffset), SM,
922 AST->getLangOpts());
923 if (Tokens.empty())
924 return;
925 for (auto I = std::rbegin(Tokens);
926 InsertionLoc.isInvalid() && I != std::rend(Tokens); ++I) {
927 switch (I->kind()) {
928 case tok::l_brace:
929 case tok::r_brace:
930 case tok::semi:
931 if (I != std::rbegin(Tokens))
932 InsertionLoc = std::prev(I)->location();
933 else
934 InsertionLoc = I->endLocation();
935 break;
936 default:
937 break;
938 }
939 }
940 if (InsertionLoc.isInvalid())
941 InsertionLoc = Tokens.front().location();
942 };
943
944 if (RelInsertPos == RelativeInsertPos::Before) {
945 InsertBefore();
946 } else {
947 // Skip over one top-level pair of parentheses (for the parameter list)
948 // and one pair of curly braces (for the code block), or `= default`.
949 // If that fails, insert before the function instead.
950 auto Tokens =
951 syntax::tokenize(syntax::FileRange(SM.getMainFileID(), *StartOffset,
952 Buffer.getBuffer().size()),
953 SM, AST->getLangOpts());
954 std::optional<syntax::Token> Tok;
955
956 // Skip parameter list (parentheses)
957 auto ClosingParen = skipTokenPair(Tokens.begin(), Tokens.end(),
958 tok::l_paren, tok::r_paren);
959 if (ClosingParen != Tokens.end()) {
960 // After the closing paren, check for `= default`
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) {
965 // Find the semicolon after `default`.
966 auto SemiIt = std::next(NextIt);
967 if (SemiIt != Tokens.end() && SemiIt->kind() == tok::semi) {
968 Tok = *SemiIt;
969 }
970 }
971 }
972
973 // If not `= default`, skip function body (braces)
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()) {
978 Tok = *ClosingBrace;
979 }
980 }
981 }
982
983 if (Tok)
984 InsertionLoc = Tok->endLocation();
985 else
986 InsertBefore();
987 }
988
989 if (!InsertionLoc.isValid())
990 return {};
991 return sourceLocToPosition(SM, InsertionLoc);
992 }
993
994 // Returns the most natural insertion point in this file.
995 // This is a fallback for when we failed to find an existing definition to
996 // place the new one next to. It only considers namespace proximity.
997 llvm::Expected<InsertionPoint> getInsertionPointInMainFile(ParsedAST *AST) {
998 // If the definition goes to the same file and there is a namespace,
999 // we should (and, in the case of anonymous namespaces, need to)
1000 // put the definition into the original namespace block.
1001 auto *Klass = Source->getDeclContext()->getOuterLexicalRecordContext();
1002 if (!Klass)
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;
1010 });
1011 while (It != Tokens.end()) {
1012 if (It->kind() != tok::semi) {
1013 ++It;
1014 continue;
1015 }
1016 unsigned Offset =
1017 AST->getSourceManager().getDecomposedLoc(It->endLocation()).second;
1018 return InsertionPoint{Klass->getEnclosingNamespaceContext(), Offset};
1019 }
1020 return error(
1021 "failed to determine insertion location: no end of class found");
1022 }
1023
1024private:
1025 const FunctionDecl *Source = nullptr;
1026 bool SameFile = false;
1027};
1028
1029REGISTER_TWEAK(DefineOutline)
1030
1031} // namespace
1032} // namespace clangd
1033} // namespace clang
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for Markdown output.")
#define REGISTER_TWEAK(Subclass)
Definition Tweak.h:129
An interface base for small context-sensitive refactoring actions.
Definition Tweak.h:46
static URI createFile(llvm::StringRef AbsolutePath)
This creates a file:// URI for AbsolutePath. The path must be absolute.
Definition URI.cpp:237
std::string toString() const
Returns a string URI with all components percent-encoded.
Definition URI.cpp:160
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
llvm::Expected< Location > indexToLSPLocation(const SymbolLocation &Loc, llvm::StringRef TUPath)
Helper function for deriving an LSP Location from an index SymbolLocation.
@ Error
An error message.
Definition Protocol.h:751
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition AST.cpp:354
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.
Definition AST.cpp:699
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)
Definition Logger.h:79
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
void log(const char *Fmt, Ts &&... Vals)
Definition Logger.h:67
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.
Definition AST.cpp:206
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
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.
Definition Protocol.h:2093
static const llvm::StringLiteral REFACTOR_KIND
Definition Protocol.h:1102
Represents a symbol occurrence in the source file.
Definition Ref.h:88
Information about a reference written in the source code, independent of the actual AST node that thi...
Definition FindTarget.h:128
Input to prepare and apply tweaks.
Definition Tweak.h:49