Extract.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. //===--- Extract.cpp - Clang refactoring library --------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief Implements the "extract" refactoring that can pull code into
  12. /// new functions, methods or declare new variables.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/Tooling/Refactoring/Extract/Extract.h"
  16. #include "SourceExtraction.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/Rewrite/Core/Rewriter.h"
  22. namespace clang {
  23. namespace tooling {
  24. namespace {
  25. /// Returns true if \c E is a simple literal or a reference expression that
  26. /// should not be extracted.
  27. bool isSimpleExpression(const Expr *E) {
  28. if (!E)
  29. return false;
  30. switch (E->IgnoreParenCasts()->getStmtClass()) {
  31. case Stmt::DeclRefExprClass:
  32. case Stmt::PredefinedExprClass:
  33. case Stmt::IntegerLiteralClass:
  34. case Stmt::FloatingLiteralClass:
  35. case Stmt::ImaginaryLiteralClass:
  36. case Stmt::CharacterLiteralClass:
  37. case Stmt::StringLiteralClass:
  38. return true;
  39. default:
  40. return false;
  41. }
  42. }
  43. SourceLocation computeFunctionExtractionLocation(const Decl *D) {
  44. if (isa<CXXMethodDecl>(D)) {
  45. // Code from method that is defined in class body should be extracted to a
  46. // function defined just before the class.
  47. while (const auto *RD = dyn_cast<CXXRecordDecl>(D->getLexicalDeclContext()))
  48. D = RD;
  49. }
  50. return D->getLocStart();
  51. }
  52. } // end anonymous namespace
  53. const RefactoringDescriptor &ExtractFunction::describe() {
  54. static const RefactoringDescriptor Descriptor = {
  55. "extract-function",
  56. "Extract Function",
  57. "(WIP action; use with caution!) Extracts code into a new function",
  58. };
  59. return Descriptor;
  60. }
  61. Expected<ExtractFunction>
  62. ExtractFunction::initiate(RefactoringRuleContext &Context,
  63. CodeRangeASTSelection Code,
  64. Optional<std::string> DeclName) {
  65. // We would like to extract code out of functions/methods/blocks.
  66. // Prohibit extraction from things like global variable / field
  67. // initializers and other top-level expressions.
  68. if (!Code.isInFunctionLikeBodyOfCode())
  69. return Context.createDiagnosticError(
  70. diag::err_refactor_code_outside_of_function);
  71. if (Code.size() == 1) {
  72. // Avoid extraction of simple literals and references.
  73. if (isSimpleExpression(dyn_cast<Expr>(Code[0])))
  74. return Context.createDiagnosticError(
  75. diag::err_refactor_extract_simple_expression);
  76. // Property setters can't be extracted.
  77. if (const auto *PRE = dyn_cast<ObjCPropertyRefExpr>(Code[0])) {
  78. if (!PRE->isMessagingGetter())
  79. return Context.createDiagnosticError(
  80. diag::err_refactor_extract_prohibited_expression);
  81. }
  82. }
  83. return ExtractFunction(std::move(Code), DeclName);
  84. }
  85. // FIXME: Support C++ method extraction.
  86. // FIXME: Support Objective-C method extraction.
  87. Expected<AtomicChanges>
  88. ExtractFunction::createSourceReplacements(RefactoringRuleContext &Context) {
  89. const Decl *ParentDecl = Code.getFunctionLikeNearestParent();
  90. assert(ParentDecl && "missing parent");
  91. // Compute the source range of the code that should be extracted.
  92. SourceRange ExtractedRange(Code[0]->getLocStart(),
  93. Code[Code.size() - 1]->getLocEnd());
  94. // FIXME (Alex L): Add code that accounts for macro locations.
  95. ASTContext &AST = Context.getASTContext();
  96. SourceManager &SM = AST.getSourceManager();
  97. const LangOptions &LangOpts = AST.getLangOpts();
  98. Rewriter ExtractedCodeRewriter(SM, LangOpts);
  99. // FIXME: Capture used variables.
  100. // Compute the return type.
  101. QualType ReturnType = AST.VoidTy;
  102. // FIXME (Alex L): Account for the return statement in extracted code.
  103. // FIXME (Alex L): Check for lexical expression instead.
  104. bool IsExpr = Code.size() == 1 && isa<Expr>(Code[0]);
  105. if (IsExpr) {
  106. // FIXME (Alex L): Get a more user-friendly type if needed.
  107. ReturnType = cast<Expr>(Code[0])->getType();
  108. }
  109. // FIXME: Rewrite the extracted code performing any required adjustments.
  110. // FIXME: Capture any field if necessary (method -> function extraction).
  111. // FIXME: Sort captured variables by name.
  112. // FIXME: Capture 'this' / 'self' if necessary.
  113. // FIXME: Compute the actual parameter types.
  114. // Compute the location of the extracted declaration.
  115. SourceLocation ExtractedDeclLocation =
  116. computeFunctionExtractionLocation(ParentDecl);
  117. // FIXME: Adjust the location to account for any preceding comments.
  118. // FIXME: Adjust with PP awareness like in Sema to get correct 'bool'
  119. // treatment.
  120. PrintingPolicy PP = AST.getPrintingPolicy();
  121. // FIXME: PP.UseStdFunctionForLambda = true;
  122. PP.SuppressStrongLifetime = true;
  123. PP.SuppressLifetimeQualifiers = true;
  124. PP.SuppressUnwrittenScope = true;
  125. ExtractionSemicolonPolicy Semicolons = ExtractionSemicolonPolicy::compute(
  126. Code[Code.size() - 1], ExtractedRange, SM, LangOpts);
  127. AtomicChange Change(SM, ExtractedDeclLocation);
  128. // Create the replacement for the extracted declaration.
  129. {
  130. std::string ExtractedCode;
  131. llvm::raw_string_ostream OS(ExtractedCode);
  132. // FIXME: Use 'inline' in header.
  133. OS << "static ";
  134. ReturnType.print(OS, PP, DeclName);
  135. OS << '(';
  136. // FIXME: Arguments.
  137. OS << ')';
  138. // Function body.
  139. OS << " {\n";
  140. if (IsExpr && !ReturnType->isVoidType())
  141. OS << "return ";
  142. OS << ExtractedCodeRewriter.getRewrittenText(ExtractedRange);
  143. if (Semicolons.isNeededInExtractedFunction())
  144. OS << ';';
  145. OS << "\n}\n\n";
  146. auto Err = Change.insert(SM, ExtractedDeclLocation, OS.str());
  147. if (Err)
  148. return std::move(Err);
  149. }
  150. // Create the replacement for the call to the extracted declaration.
  151. {
  152. std::string ReplacedCode;
  153. llvm::raw_string_ostream OS(ReplacedCode);
  154. OS << DeclName << '(';
  155. // FIXME: Forward arguments.
  156. OS << ')';
  157. if (Semicolons.isNeededInOriginalFunction())
  158. OS << ';';
  159. auto Err = Change.replace(
  160. SM, CharSourceRange::getTokenRange(ExtractedRange), OS.str());
  161. if (Err)
  162. return std::move(Err);
  163. }
  164. // FIXME: Add support for assocciated symbol location to AtomicChange to mark
  165. // the ranges of the name of the extracted declaration.
  166. return AtomicChanges{std::move(Change)};
  167. }
  168. } // end namespace tooling
  169. } // end namespace clang