1 //===--- ExtractFunction.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 // Extracts statements to a new function and replaces the statements with a 10 // call to the new function. 11 // Before: 12 // void f(int a) { 13 // [[if(a < 5) 14 // a = 5;]] 15 // } 16 // After: 17 // void extracted(int &a) { 18 // if(a < 5) 19 // a = 5; 20 // } 21 // void f(int a) { 22 // extracted(a); 23 // } 24 // 25 // - Only extract statements 26 // - Extracts from non-templated free functions only. 27 // - Parameters are const only if the declaration was const 28 // - Always passed by l-value reference 29 // - Void return type 30 // - Cannot extract declarations that will be needed in the original function 31 // after extraction. 32 // - Checks for broken control flow (break/continue without loop/switch) 33 // 34 // 1. ExtractFunction is the tweak subclass 35 // - Prepare does basic analysis of the selection and is therefore fast. 36 // Successful prepare doesn't always mean we can apply the tweak. 37 // - Apply does a more detailed analysis and can be slower. In case of 38 // failure, we let the user know that we are unable to perform extraction. 39 // 2. ExtractionZone store information about the range being extracted and the 40 // enclosing function. 41 // 3. NewFunction stores properties of the extracted function and provides 42 // methods for rendering it. 43 // 4. CapturedZoneInfo uses a RecursiveASTVisitor to capture information about 44 // the extraction like declarations, existing return statements, etc. 45 // 5. getExtractedFunction is responsible for analyzing the CapturedZoneInfo and 46 // creating a NewFunction. 47 //===----------------------------------------------------------------------===// 48 49 #include "AST.h" 50 #include "FindTarget.h" 51 #include "ParsedAST.h" 52 #include "Selection.h" 53 #include "SourceCode.h" 54 #include "refactor/Tweak.h" 55 #include "support/Logger.h" 56 #include "clang/AST/ASTContext.h" 57 #include "clang/AST/Decl.h" 58 #include "clang/AST/DeclBase.h" 59 #include "clang/AST/RecursiveASTVisitor.h" 60 #include "clang/AST/Stmt.h" 61 #include "clang/Basic/LangOptions.h" 62 #include "clang/Basic/SourceLocation.h" 63 #include "clang/Basic/SourceManager.h" 64 #include "clang/Tooling/Core/Replacement.h" 65 #include "clang/Tooling/Refactoring/Extract/SourceExtraction.h" 66 #include "llvm/ADT/None.h" 67 #include "llvm/ADT/Optional.h" 68 #include "llvm/ADT/STLExtras.h" 69 #include "llvm/ADT/SmallSet.h" 70 #include "llvm/ADT/SmallVector.h" 71 #include "llvm/ADT/StringRef.h" 72 #include "llvm/Support/Casting.h" 73 #include "llvm/Support/Error.h" 74 75 namespace clang { 76 namespace clangd { 77 namespace { 78 79 using Node = SelectionTree::Node; 80 81 // ExtractionZone is the part of code that is being extracted. 82 // EnclosingFunction is the function/method inside which the zone lies. 83 // We split the file into 4 parts relative to extraction zone. 84 enum class ZoneRelative { 85 Before, // Before Zone and inside EnclosingFunction. 86 Inside, // Inside Zone. 87 After, // After Zone and inside EnclosingFunction. 88 OutsideFunc // Outside EnclosingFunction. 89 }; 90 91 // A RootStmt is a statement that's fully selected including all it's children 92 // and it's parent is unselected. 93 // Check if a node is a root statement. 94 bool isRootStmt(const Node *N) { 95 if (!N->ASTNode.get<Stmt>()) 96 return false; 97 // Root statement cannot be partially selected. 98 if (N->Selected == SelectionTree::Partial) 99 return false; 100 // Only DeclStmt can be an unselected RootStmt since VarDecls claim the entire 101 // selection range in selectionTree. 102 if (N->Selected == SelectionTree::Unselected && !N->ASTNode.get<DeclStmt>()) 103 return false; 104 return true; 105 } 106 107 // Returns the (unselected) parent of all RootStmts given the commonAncestor. 108 // Returns null if: 109 // 1. any node is partially selected 110 // 2. If all completely selected nodes don't have the same common parent 111 // 3. Any child of Parent isn't a RootStmt. 112 // Returns null if any child is not a RootStmt. 113 // We only support extraction of RootStmts since it allows us to extract without 114 // having to change the selection range. Also, this means that any scope that 115 // begins in selection range, ends in selection range and any scope that begins 116 // outside the selection range, ends outside as well. 117 const Node *getParentOfRootStmts(const Node *CommonAnc) { 118 if (!CommonAnc) 119 return nullptr; 120 const Node *Parent = nullptr; 121 switch (CommonAnc->Selected) { 122 case SelectionTree::Selection::Unselected: 123 // Typically a block, with the { and } unselected, could also be ForStmt etc 124 // Ensure all Children are RootStmts. 125 Parent = CommonAnc; 126 break; 127 case SelectionTree::Selection::Partial: 128 // Only a fully-selected single statement can be selected. 129 return nullptr; 130 case SelectionTree::Selection::Complete: 131 // If the Common Ancestor is completely selected, then it's a root statement 132 // and its parent will be unselected. 133 Parent = CommonAnc->Parent; 134 // If parent is a DeclStmt, even though it's unselected, we consider it a 135 // root statement and return its parent. This is done because the VarDecls 136 // claim the entire selection range of the Declaration and DeclStmt is 137 // always unselected. 138 if (Parent->ASTNode.get<DeclStmt>()) 139 Parent = Parent->Parent; 140 break; 141 } 142 // Ensure all Children are RootStmts. 143 return llvm::all_of(Parent->Children, isRootStmt) ? Parent : nullptr; 144 } 145 146 // The ExtractionZone class forms a view of the code wrt Zone. 147 struct ExtractionZone { 148 // Parent of RootStatements being extracted. 149 const Node *Parent = nullptr; 150 // The half-open file range of the code being extracted. 151 SourceRange ZoneRange; 152 // The function inside which our zone resides. 153 const FunctionDecl *EnclosingFunction = nullptr; 154 // The half-open file range of the enclosing function. 155 SourceRange EnclosingFuncRange; 156 // Set of statements that form the ExtractionZone. 157 llvm::DenseSet<const Stmt *> RootStmts; 158 159 SourceLocation getInsertionPoint() const { 160 return EnclosingFuncRange.getBegin(); 161 } 162 bool isRootStmt(const Stmt *S) const; 163 // The last root statement is important to decide where we need to insert a 164 // semicolon after the extraction. 165 const Node *getLastRootStmt() const { return Parent->Children.back(); } 166 167 // Checks if declarations inside extraction zone are accessed afterwards. 168 // 169 // This performs a partial AST traversal proportional to the size of the 170 // enclosing function, so it is possibly expensive. 171 bool requiresHoisting(const SourceManager &SM, 172 const HeuristicResolver *Resolver) const { 173 // First find all the declarations that happened inside extraction zone. 174 llvm::SmallSet<const Decl *, 1> DeclsInExtZone; 175 for (auto *RootStmt : RootStmts) { 176 findExplicitReferences( 177 RootStmt, 178 [&DeclsInExtZone](const ReferenceLoc &Loc) { 179 if (!Loc.IsDecl) 180 return; 181 DeclsInExtZone.insert(Loc.Targets.front()); 182 }, 183 Resolver); 184 } 185 // Early exit without performing expensive traversal below. 186 if (DeclsInExtZone.empty()) 187 return false; 188 // Then make sure they are not used outside the zone. 189 for (const auto *S : EnclosingFunction->getBody()->children()) { 190 if (SM.isBeforeInTranslationUnit(S->getSourceRange().getEnd(), 191 ZoneRange.getEnd())) 192 continue; 193 bool HasPostUse = false; 194 findExplicitReferences( 195 S, 196 [&](const ReferenceLoc &Loc) { 197 if (HasPostUse || 198 SM.isBeforeInTranslationUnit(Loc.NameLoc, ZoneRange.getEnd())) 199 return; 200 HasPostUse = llvm::any_of(Loc.Targets, 201 [&DeclsInExtZone](const Decl *Target) { 202 return DeclsInExtZone.contains(Target); 203 }); 204 }, 205 Resolver); 206 if (HasPostUse) 207 return true; 208 } 209 return false; 210 } 211 }; 212 213 // Whether the code in the extraction zone is guaranteed to return, assuming 214 // no broken control flow (unbound break/continue). 215 // This is a very naive check (does it end with a return stmt). 216 // Doing some rudimentary control flow analysis would cover more cases. 217 bool alwaysReturns(const ExtractionZone &EZ) { 218 const Stmt *Last = EZ.getLastRootStmt()->ASTNode.get<Stmt>(); 219 // Unwrap enclosing (unconditional) compound statement. 220 while (const auto *CS = llvm::dyn_cast<CompoundStmt>(Last)) { 221 if (CS->body_empty()) 222 return false; 223 Last = CS->body_back(); 224 } 225 return llvm::isa<ReturnStmt>(Last); 226 } 227 228 bool ExtractionZone::isRootStmt(const Stmt *S) const { 229 return RootStmts.contains(S); 230 } 231 232 // Finds the function in which the zone lies. 233 const FunctionDecl *findEnclosingFunction(const Node *CommonAnc) { 234 // Walk up the SelectionTree until we find a function Decl 235 for (const Node *CurNode = CommonAnc; CurNode; CurNode = CurNode->Parent) { 236 // Don't extract from lambdas 237 if (CurNode->ASTNode.get<LambdaExpr>()) 238 return nullptr; 239 if (const FunctionDecl *Func = CurNode->ASTNode.get<FunctionDecl>()) { 240 // FIXME: Support extraction from methods. 241 if (isa<CXXMethodDecl>(Func)) 242 return nullptr; 243 // FIXME: Support extraction from templated functions. 244 if (Func->isTemplated()) 245 return nullptr; 246 return Func; 247 } 248 } 249 return nullptr; 250 } 251 252 // Zone Range is the union of SourceRanges of all child Nodes in Parent since 253 // all child Nodes are RootStmts 254 llvm::Optional<SourceRange> findZoneRange(const Node *Parent, 255 const SourceManager &SM, 256 const LangOptions &LangOpts) { 257 SourceRange SR; 258 if (auto BeginFileRange = toHalfOpenFileRange( 259 SM, LangOpts, Parent->Children.front()->ASTNode.getSourceRange())) 260 SR.setBegin(BeginFileRange->getBegin()); 261 else 262 return llvm::None; 263 if (auto EndFileRange = toHalfOpenFileRange( 264 SM, LangOpts, Parent->Children.back()->ASTNode.getSourceRange())) 265 SR.setEnd(EndFileRange->getEnd()); 266 else 267 return llvm::None; 268 return SR; 269 } 270 271 // Compute the range spanned by the enclosing function. 272 // FIXME: check if EnclosingFunction has any attributes as the AST doesn't 273 // always store the source range of the attributes and thus we end up extracting 274 // between the attributes and the EnclosingFunction. 275 llvm::Optional<SourceRange> 276 computeEnclosingFuncRange(const FunctionDecl *EnclosingFunction, 277 const SourceManager &SM, 278 const LangOptions &LangOpts) { 279 return toHalfOpenFileRange(SM, LangOpts, EnclosingFunction->getSourceRange()); 280 } 281 282 // returns true if Child can be a single RootStmt being extracted from 283 // EnclosingFunc. 284 bool validSingleChild(const Node *Child, const FunctionDecl *EnclosingFunc) { 285 // Don't extract expressions. 286 // FIXME: We should extract expressions that are "statements" i.e. not 287 // subexpressions 288 if (Child->ASTNode.get<Expr>()) 289 return false; 290 // Extracting the body of EnclosingFunc would remove it's definition. 291 assert(EnclosingFunc->hasBody() && 292 "We should always be extracting from a function body."); 293 if (Child->ASTNode.get<Stmt>() == EnclosingFunc->getBody()) 294 return false; 295 return true; 296 } 297 298 // FIXME: Check we're not extracting from the initializer/condition of a control 299 // flow structure. 300 llvm::Optional<ExtractionZone> findExtractionZone(const Node *CommonAnc, 301 const SourceManager &SM, 302 const LangOptions &LangOpts) { 303 ExtractionZone ExtZone; 304 ExtZone.Parent = getParentOfRootStmts(CommonAnc); 305 if (!ExtZone.Parent || ExtZone.Parent->Children.empty()) 306 return llvm::None; 307 ExtZone.EnclosingFunction = findEnclosingFunction(ExtZone.Parent); 308 if (!ExtZone.EnclosingFunction) 309 return llvm::None; 310 // When there is a single RootStmt, we must check if it's valid for 311 // extraction. 312 if (ExtZone.Parent->Children.size() == 1 && 313 !validSingleChild(ExtZone.getLastRootStmt(), ExtZone.EnclosingFunction)) 314 return llvm::None; 315 if (auto FuncRange = 316 computeEnclosingFuncRange(ExtZone.EnclosingFunction, SM, LangOpts)) 317 ExtZone.EnclosingFuncRange = *FuncRange; 318 if (auto ZoneRange = findZoneRange(ExtZone.Parent, SM, LangOpts)) 319 ExtZone.ZoneRange = *ZoneRange; 320 if (ExtZone.EnclosingFuncRange.isInvalid() || ExtZone.ZoneRange.isInvalid()) 321 return llvm::None; 322 323 for (const Node *Child : ExtZone.Parent->Children) 324 ExtZone.RootStmts.insert(Child->ASTNode.get<Stmt>()); 325 326 return ExtZone; 327 } 328 329 // Stores information about the extracted function and provides methods for 330 // rendering it. 331 struct NewFunction { 332 struct Parameter { 333 std::string Name; 334 QualType TypeInfo; 335 bool PassByReference; 336 unsigned OrderPriority; // Lower value parameters are preferred first. 337 std::string render(const DeclContext *Context) const; 338 bool operator<(const Parameter &Other) const { 339 return OrderPriority < Other.OrderPriority; 340 } 341 }; 342 std::string Name = "extracted"; 343 QualType ReturnType; 344 std::vector<Parameter> Parameters; 345 SourceRange BodyRange; 346 SourceLocation InsertionPoint; 347 const DeclContext *EnclosingFuncContext; 348 bool CallerReturnsValue = false; 349 // Decides whether the extracted function body and the function call need a 350 // semicolon after extraction. 351 tooling::ExtractionSemicolonPolicy SemicolonPolicy; 352 NewFunction(tooling::ExtractionSemicolonPolicy SemicolonPolicy) 353 : SemicolonPolicy(SemicolonPolicy) {} 354 // Render the call for this function. 355 std::string renderCall() const; 356 // Render the definition for this function. 357 std::string renderDefinition(const SourceManager &SM) const; 358 359 private: 360 std::string renderParametersForDefinition() const; 361 std::string renderParametersForCall() const; 362 // Generate the function body. 363 std::string getFuncBody(const SourceManager &SM) const; 364 }; 365 366 std::string NewFunction::renderParametersForDefinition() const { 367 std::string Result; 368 bool NeedCommaBefore = false; 369 for (const Parameter &P : Parameters) { 370 if (NeedCommaBefore) 371 Result += ", "; 372 NeedCommaBefore = true; 373 Result += P.render(EnclosingFuncContext); 374 } 375 return Result; 376 } 377 378 std::string NewFunction::renderParametersForCall() const { 379 std::string Result; 380 bool NeedCommaBefore = false; 381 for (const Parameter &P : Parameters) { 382 if (NeedCommaBefore) 383 Result += ", "; 384 NeedCommaBefore = true; 385 Result += P.Name; 386 } 387 return Result; 388 } 389 390 std::string NewFunction::renderCall() const { 391 return std::string( 392 llvm::formatv("{0}{1}({2}){3}", CallerReturnsValue ? "return " : "", Name, 393 renderParametersForCall(), 394 (SemicolonPolicy.isNeededInOriginalFunction() ? ";" : ""))); 395 } 396 397 std::string NewFunction::renderDefinition(const SourceManager &SM) const { 398 return std::string(llvm::formatv( 399 "{0} {1}({2}) {\n{3}\n}\n", printType(ReturnType, *EnclosingFuncContext), 400 Name, renderParametersForDefinition(), getFuncBody(SM))); 401 } 402 403 std::string NewFunction::getFuncBody(const SourceManager &SM) const { 404 // FIXME: Generate tooling::Replacements instead of std::string to 405 // - hoist decls 406 // - add return statement 407 // - Add semicolon 408 return toSourceCode(SM, BodyRange).str() + 409 (SemicolonPolicy.isNeededInExtractedFunction() ? ";" : ""); 410 } 411 412 std::string NewFunction::Parameter::render(const DeclContext *Context) const { 413 return printType(TypeInfo, *Context) + (PassByReference ? " &" : " ") + Name; 414 } 415 416 // Stores captured information about Extraction Zone. 417 struct CapturedZoneInfo { 418 struct DeclInformation { 419 const Decl *TheDecl; 420 ZoneRelative DeclaredIn; 421 // index of the declaration or first reference. 422 unsigned DeclIndex; 423 bool IsReferencedInZone = false; 424 bool IsReferencedInPostZone = false; 425 // FIXME: Capture mutation information 426 DeclInformation(const Decl *TheDecl, ZoneRelative DeclaredIn, 427 unsigned DeclIndex) 428 : TheDecl(TheDecl), DeclaredIn(DeclaredIn), DeclIndex(DeclIndex){}; 429 // Marks the occurence of a reference for this declaration 430 void markOccurence(ZoneRelative ReferenceLoc); 431 }; 432 // Maps Decls to their DeclInfo 433 llvm::DenseMap<const Decl *, DeclInformation> DeclInfoMap; 434 bool HasReturnStmt = false; // Are there any return statements in the zone? 435 bool AlwaysReturns = false; // Does the zone always return? 436 // Control flow is broken if we are extracting a break/continue without a 437 // corresponding parent loop/switch 438 bool BrokenControlFlow = false; 439 // FIXME: capture TypeAliasDecl and UsingDirectiveDecl 440 // FIXME: Capture type information as well. 441 DeclInformation *createDeclInfo(const Decl *D, ZoneRelative RelativeLoc); 442 DeclInformation *getDeclInfoFor(const Decl *D); 443 }; 444 445 CapturedZoneInfo::DeclInformation * 446 CapturedZoneInfo::createDeclInfo(const Decl *D, ZoneRelative RelativeLoc) { 447 // The new Decl's index is the size of the map so far. 448 auto InsertionResult = DeclInfoMap.insert( 449 {D, DeclInformation(D, RelativeLoc, DeclInfoMap.size())}); 450 // Return the newly created DeclInfo 451 return &InsertionResult.first->second; 452 } 453 454 CapturedZoneInfo::DeclInformation * 455 CapturedZoneInfo::getDeclInfoFor(const Decl *D) { 456 // If the Decl doesn't exist, we 457 auto Iter = DeclInfoMap.find(D); 458 if (Iter == DeclInfoMap.end()) 459 return nullptr; 460 return &Iter->second; 461 } 462 463 void CapturedZoneInfo::DeclInformation::markOccurence( 464 ZoneRelative ReferenceLoc) { 465 switch (ReferenceLoc) { 466 case ZoneRelative::Inside: 467 IsReferencedInZone = true; 468 break; 469 case ZoneRelative::After: 470 IsReferencedInPostZone = true; 471 break; 472 default: 473 break; 474 } 475 } 476 477 bool isLoop(const Stmt *S) { 478 return isa<ForStmt>(S) || isa<DoStmt>(S) || isa<WhileStmt>(S) || 479 isa<CXXForRangeStmt>(S); 480 } 481 482 // Captures information from Extraction Zone 483 CapturedZoneInfo captureZoneInfo(const ExtractionZone &ExtZone) { 484 // We use the ASTVisitor instead of using the selection tree since we need to 485 // find references in the PostZone as well. 486 // FIXME: Check which statements we don't allow to extract. 487 class ExtractionZoneVisitor 488 : public clang::RecursiveASTVisitor<ExtractionZoneVisitor> { 489 public: 490 ExtractionZoneVisitor(const ExtractionZone &ExtZone) : ExtZone(ExtZone) { 491 TraverseDecl(const_cast<FunctionDecl *>(ExtZone.EnclosingFunction)); 492 } 493 494 bool TraverseStmt(Stmt *S) { 495 if (!S) 496 return true; 497 bool IsRootStmt = ExtZone.isRootStmt(const_cast<const Stmt *>(S)); 498 // If we are starting traversal of a RootStmt, we are somewhere inside 499 // ExtractionZone 500 if (IsRootStmt) 501 CurrentLocation = ZoneRelative::Inside; 502 addToLoopSwitchCounters(S, 1); 503 // Traverse using base class's TraverseStmt 504 RecursiveASTVisitor::TraverseStmt(S); 505 addToLoopSwitchCounters(S, -1); 506 // We set the current location as after since next stmt will either be a 507 // RootStmt (handled at the beginning) or after extractionZone 508 if (IsRootStmt) 509 CurrentLocation = ZoneRelative::After; 510 return true; 511 } 512 513 // Add Increment to CurNumberOf{Loops,Switch} if statement is 514 // {Loop,Switch} and inside Extraction Zone. 515 void addToLoopSwitchCounters(Stmt *S, int Increment) { 516 if (CurrentLocation != ZoneRelative::Inside) 517 return; 518 if (isLoop(S)) 519 CurNumberOfNestedLoops += Increment; 520 else if (isa<SwitchStmt>(S)) 521 CurNumberOfSwitch += Increment; 522 } 523 524 bool VisitDecl(Decl *D) { 525 Info.createDeclInfo(D, CurrentLocation); 526 return true; 527 } 528 529 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 530 // Find the corresponding Decl and mark it's occurrence. 531 const Decl *D = DRE->getDecl(); 532 auto *DeclInfo = Info.getDeclInfoFor(D); 533 // If no Decl was found, the Decl must be outside the enclosingFunc. 534 if (!DeclInfo) 535 DeclInfo = Info.createDeclInfo(D, ZoneRelative::OutsideFunc); 536 DeclInfo->markOccurence(CurrentLocation); 537 // FIXME: check if reference mutates the Decl being referred. 538 return true; 539 } 540 541 bool VisitReturnStmt(ReturnStmt *Return) { 542 if (CurrentLocation == ZoneRelative::Inside) 543 Info.HasReturnStmt = true; 544 return true; 545 } 546 547 bool VisitBreakStmt(BreakStmt *Break) { 548 // Control flow is broken if break statement is selected without any 549 // parent loop or switch statement. 550 if (CurrentLocation == ZoneRelative::Inside && 551 !(CurNumberOfNestedLoops || CurNumberOfSwitch)) 552 Info.BrokenControlFlow = true; 553 return true; 554 } 555 556 bool VisitContinueStmt(ContinueStmt *Continue) { 557 // Control flow is broken if Continue statement is selected without any 558 // parent loop 559 if (CurrentLocation == ZoneRelative::Inside && !CurNumberOfNestedLoops) 560 Info.BrokenControlFlow = true; 561 return true; 562 } 563 CapturedZoneInfo Info; 564 const ExtractionZone &ExtZone; 565 ZoneRelative CurrentLocation = ZoneRelative::Before; 566 // Number of {loop,switch} statements that are currently in the traversal 567 // stack inside Extraction Zone. Used to check for broken control flow. 568 unsigned CurNumberOfNestedLoops = 0; 569 unsigned CurNumberOfSwitch = 0; 570 }; 571 ExtractionZoneVisitor Visitor(ExtZone); 572 CapturedZoneInfo Result = std::move(Visitor.Info); 573 Result.AlwaysReturns = alwaysReturns(ExtZone); 574 return Result; 575 } 576 577 // Adds parameters to ExtractedFunc. 578 // Returns true if able to find the parameters successfully and no hoisting 579 // needed. 580 // FIXME: Check if the declaration has a local/anonymous type 581 bool createParameters(NewFunction &ExtractedFunc, 582 const CapturedZoneInfo &CapturedInfo) { 583 for (const auto &KeyVal : CapturedInfo.DeclInfoMap) { 584 const auto &DeclInfo = KeyVal.second; 585 // If a Decl was Declared in zone and referenced in post zone, it 586 // needs to be hoisted (we bail out in that case). 587 // FIXME: Support Decl Hoisting. 588 if (DeclInfo.DeclaredIn == ZoneRelative::Inside && 589 DeclInfo.IsReferencedInPostZone) 590 return false; 591 if (!DeclInfo.IsReferencedInZone) 592 continue; // no need to pass as parameter, not referenced 593 if (DeclInfo.DeclaredIn == ZoneRelative::Inside || 594 DeclInfo.DeclaredIn == ZoneRelative::OutsideFunc) 595 continue; // no need to pass as parameter, still accessible. 596 // Parameter specific checks. 597 const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(DeclInfo.TheDecl); 598 // Can't parameterise if the Decl isn't a ValueDecl or is a FunctionDecl 599 // (this includes the case of recursive call to EnclosingFunc in Zone). 600 if (!VD || isa<FunctionDecl>(DeclInfo.TheDecl)) 601 return false; 602 // Parameter qualifiers are same as the Decl's qualifiers. 603 QualType TypeInfo = VD->getType().getNonReferenceType(); 604 // FIXME: Need better qualifier checks: check mutated status for 605 // Decl(e.g. was it assigned, passed as nonconst argument, etc) 606 // FIXME: check if parameter will be a non l-value reference. 607 // FIXME: We don't want to always pass variables of types like int, 608 // pointers, etc by reference. 609 bool IsPassedByReference = true; 610 // We use the index of declaration as the ordering priority for parameters. 611 ExtractedFunc.Parameters.push_back({std::string(VD->getName()), TypeInfo, 612 IsPassedByReference, 613 DeclInfo.DeclIndex}); 614 } 615 llvm::sort(ExtractedFunc.Parameters); 616 return true; 617 } 618 619 // Clangd uses open ranges while ExtractionSemicolonPolicy (in Clang Tooling) 620 // uses closed ranges. Generates the semicolon policy for the extraction and 621 // extends the ZoneRange if necessary. 622 tooling::ExtractionSemicolonPolicy 623 getSemicolonPolicy(ExtractionZone &ExtZone, const SourceManager &SM, 624 const LangOptions &LangOpts) { 625 // Get closed ZoneRange. 626 SourceRange FuncBodyRange = {ExtZone.ZoneRange.getBegin(), 627 ExtZone.ZoneRange.getEnd().getLocWithOffset(-1)}; 628 auto SemicolonPolicy = tooling::ExtractionSemicolonPolicy::compute( 629 ExtZone.getLastRootStmt()->ASTNode.get<Stmt>(), FuncBodyRange, SM, 630 LangOpts); 631 // Update ZoneRange. 632 ExtZone.ZoneRange.setEnd(FuncBodyRange.getEnd().getLocWithOffset(1)); 633 return SemicolonPolicy; 634 } 635 636 // Generate return type for ExtractedFunc. Return false if unable to do so. 637 bool generateReturnProperties(NewFunction &ExtractedFunc, 638 const FunctionDecl &EnclosingFunc, 639 const CapturedZoneInfo &CapturedInfo) { 640 // If the selected code always returns, we preserve those return statements. 641 // The return type should be the same as the enclosing function. 642 // (Others are possible if there are conversions, but this seems clearest). 643 if (CapturedInfo.HasReturnStmt) { 644 // If the return is conditional, neither replacing the code with 645 // `extracted()` nor `return extracted()` is correct. 646 if (!CapturedInfo.AlwaysReturns) 647 return false; 648 QualType Ret = EnclosingFunc.getReturnType(); 649 // Once we support members, it'd be nice to support e.g. extracting a method 650 // of Foo<T> that returns T. But it's not clear when that's safe. 651 if (Ret->isDependentType()) 652 return false; 653 ExtractedFunc.ReturnType = Ret; 654 return true; 655 } 656 // FIXME: Generate new return statement if needed. 657 ExtractedFunc.ReturnType = EnclosingFunc.getParentASTContext().VoidTy; 658 return true; 659 } 660 661 // FIXME: add support for adding other function return types besides void. 662 // FIXME: assign the value returned by non void extracted function. 663 llvm::Expected<NewFunction> getExtractedFunction(ExtractionZone &ExtZone, 664 const SourceManager &SM, 665 const LangOptions &LangOpts) { 666 CapturedZoneInfo CapturedInfo = captureZoneInfo(ExtZone); 667 // Bail out if any break of continue exists 668 if (CapturedInfo.BrokenControlFlow) 669 return error("Cannot extract break/continue without corresponding " 670 "loop/switch statement."); 671 NewFunction ExtractedFunc(getSemicolonPolicy(ExtZone, SM, LangOpts)); 672 ExtractedFunc.BodyRange = ExtZone.ZoneRange; 673 ExtractedFunc.InsertionPoint = ExtZone.getInsertionPoint(); 674 ExtractedFunc.EnclosingFuncContext = 675 ExtZone.EnclosingFunction->getDeclContext(); 676 ExtractedFunc.CallerReturnsValue = CapturedInfo.AlwaysReturns; 677 if (!createParameters(ExtractedFunc, CapturedInfo) || 678 !generateReturnProperties(ExtractedFunc, *ExtZone.EnclosingFunction, 679 CapturedInfo)) 680 return error("Too complex to extract."); 681 return ExtractedFunc; 682 } 683 684 class ExtractFunction : public Tweak { 685 public: 686 const char *id() const override final; 687 bool prepare(const Selection &Inputs) override; 688 Expected<Effect> apply(const Selection &Inputs) override; 689 std::string title() const override { return "Extract to function"; } 690 llvm::StringLiteral kind() const override { 691 return CodeAction::REFACTOR_KIND; 692 } 693 694 private: 695 ExtractionZone ExtZone; 696 }; 697 698 REGISTER_TWEAK(ExtractFunction) 699 tooling::Replacement replaceWithFuncCall(const NewFunction &ExtractedFunc, 700 const SourceManager &SM, 701 const LangOptions &LangOpts) { 702 std::string FuncCall = ExtractedFunc.renderCall(); 703 return tooling::Replacement( 704 SM, CharSourceRange(ExtractedFunc.BodyRange, false), FuncCall, LangOpts); 705 } 706 707 tooling::Replacement createFunctionDefinition(const NewFunction &ExtractedFunc, 708 const SourceManager &SM) { 709 std::string FunctionDef = ExtractedFunc.renderDefinition(SM); 710 return tooling::Replacement(SM, ExtractedFunc.InsertionPoint, 0, FunctionDef); 711 } 712 713 // Returns true if ExtZone contains any ReturnStmts. 714 bool hasReturnStmt(const ExtractionZone &ExtZone) { 715 class ReturnStmtVisitor 716 : public clang::RecursiveASTVisitor<ReturnStmtVisitor> { 717 public: 718 bool VisitReturnStmt(ReturnStmt *Return) { 719 Found = true; 720 return false; // We found the answer, abort the scan. 721 } 722 bool Found = false; 723 }; 724 725 ReturnStmtVisitor V; 726 for (const Stmt *RootStmt : ExtZone.RootStmts) { 727 V.TraverseStmt(const_cast<Stmt *>(RootStmt)); 728 if (V.Found) 729 break; 730 } 731 return V.Found; 732 } 733 734 bool ExtractFunction::prepare(const Selection &Inputs) { 735 const LangOptions &LangOpts = Inputs.AST->getLangOpts(); 736 if (!LangOpts.CPlusPlus) 737 return false; 738 const Node *CommonAnc = Inputs.ASTSelection.commonAncestor(); 739 const SourceManager &SM = Inputs.AST->getSourceManager(); 740 auto MaybeExtZone = findExtractionZone(CommonAnc, SM, LangOpts); 741 if (!MaybeExtZone || 742 (hasReturnStmt(*MaybeExtZone) && !alwaysReturns(*MaybeExtZone))) 743 return false; 744 745 // FIXME: Get rid of this check once we support hoisting. 746 if (MaybeExtZone->requiresHoisting(SM, Inputs.AST->getHeuristicResolver())) 747 return false; 748 749 ExtZone = std::move(*MaybeExtZone); 750 return true; 751 } 752 753 Expected<Tweak::Effect> ExtractFunction::apply(const Selection &Inputs) { 754 const SourceManager &SM = Inputs.AST->getSourceManager(); 755 const LangOptions &LangOpts = Inputs.AST->getLangOpts(); 756 auto ExtractedFunc = getExtractedFunction(ExtZone, SM, LangOpts); 757 // FIXME: Add more types of errors. 758 if (!ExtractedFunc) 759 return ExtractedFunc.takeError(); 760 tooling::Replacements Result; 761 if (auto Err = Result.add(createFunctionDefinition(*ExtractedFunc, SM))) 762 return std::move(Err); 763 if (auto Err = Result.add(replaceWithFuncCall(*ExtractedFunc, SM, LangOpts))) 764 return std::move(Err); 765 return Effect::mainFileEdit(SM, std::move(Result)); 766 } 767 768 } // namespace 769 } // namespace clangd 770 } // namespace clang 771