SourceCodeBuilders.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. //===--- SourceCodeBuilder.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. #include "clang/Tooling/Transformer/SourceCodeBuilders.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/AST/Expr.h"
  11. #include "clang/AST/ExprCXX.h"
  12. #include "clang/ASTMatchers/ASTMatchFinder.h"
  13. #include "clang/ASTMatchers/ASTMatchers.h"
  14. #include "clang/Tooling/Transformer/SourceCode.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include <string>
  17. using namespace clang;
  18. using namespace tooling;
  19. const Expr *tooling::reallyIgnoreImplicit(const Expr &E) {
  20. const Expr *Expr = E.IgnoreImplicit();
  21. if (const auto *CE = dyn_cast<CXXConstructExpr>(Expr)) {
  22. if (CE->getNumArgs() > 0 &&
  23. CE->getArg(0)->getSourceRange() == Expr->getSourceRange())
  24. return CE->getArg(0)->IgnoreImplicit();
  25. }
  26. return Expr;
  27. }
  28. bool tooling::mayEverNeedParens(const Expr &E) {
  29. const Expr *Expr = reallyIgnoreImplicit(E);
  30. // We always want parens around unary, binary, and ternary operators, because
  31. // they are lower precedence.
  32. if (isa<UnaryOperator>(Expr) || isa<BinaryOperator>(Expr) ||
  33. isa<AbstractConditionalOperator>(Expr))
  34. return true;
  35. // We need parens around calls to all overloaded operators except: function
  36. // calls, subscripts, and expressions that are already part of an (implicit)
  37. // call to operator->. These latter are all in the same precedence level as
  38. // dot/arrow and that level is left associative, so they don't need parens
  39. // when appearing on the left.
  40. if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(Expr))
  41. return Op->getOperator() != OO_Call && Op->getOperator() != OO_Subscript &&
  42. Op->getOperator() != OO_Arrow;
  43. return false;
  44. }
  45. bool tooling::needParensAfterUnaryOperator(const Expr &E) {
  46. const Expr *Expr = reallyIgnoreImplicit(E);
  47. if (isa<BinaryOperator>(Expr) || isa<AbstractConditionalOperator>(Expr))
  48. return true;
  49. if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(Expr))
  50. return Op->getNumArgs() == 2 && Op->getOperator() != OO_PlusPlus &&
  51. Op->getOperator() != OO_MinusMinus && Op->getOperator() != OO_Call &&
  52. Op->getOperator() != OO_Subscript;
  53. return false;
  54. }
  55. bool tooling::isKnownPointerLikeType(QualType Ty, ASTContext &Context) {
  56. using namespace ast_matchers;
  57. const auto PointerLikeTy = type(hasUnqualifiedDesugaredType(
  58. recordType(hasDeclaration(cxxRecordDecl(hasAnyName(
  59. "::std::unique_ptr", "::std::shared_ptr", "::std::weak_ptr",
  60. "::std::optional", "::absl::optional", "::llvm::Optional",
  61. "absl::StatusOr", "::llvm::Expected"))))));
  62. return match(PointerLikeTy, Ty, Context).size() > 0;
  63. }
  64. llvm::Optional<std::string> tooling::buildParens(const Expr &E,
  65. const ASTContext &Context) {
  66. StringRef Text = getText(E, Context);
  67. if (Text.empty())
  68. return llvm::None;
  69. if (mayEverNeedParens(E))
  70. return ("(" + Text + ")").str();
  71. return Text.str();
  72. }
  73. llvm::Optional<std::string>
  74. tooling::buildDereference(const Expr &E, const ASTContext &Context) {
  75. if (const auto *Op = dyn_cast<UnaryOperator>(&E))
  76. if (Op->getOpcode() == UO_AddrOf) {
  77. // Strip leading '&'.
  78. StringRef Text =
  79. getText(*Op->getSubExpr()->IgnoreParenImpCasts(), Context);
  80. if (Text.empty())
  81. return llvm::None;
  82. return Text.str();
  83. }
  84. StringRef Text = getText(E, Context);
  85. if (Text.empty())
  86. return llvm::None;
  87. // Add leading '*'.
  88. if (needParensAfterUnaryOperator(E))
  89. return ("*(" + Text + ")").str();
  90. return ("*" + Text).str();
  91. }
  92. llvm::Optional<std::string> tooling::buildAddressOf(const Expr &E,
  93. const ASTContext &Context) {
  94. if (E.isImplicitCXXThis())
  95. return std::string("this");
  96. if (const auto *Op = dyn_cast<UnaryOperator>(&E))
  97. if (Op->getOpcode() == UO_Deref) {
  98. // Strip leading '*'.
  99. StringRef Text =
  100. getText(*Op->getSubExpr()->IgnoreParenImpCasts(), Context);
  101. if (Text.empty())
  102. return llvm::None;
  103. return Text.str();
  104. }
  105. // Add leading '&'.
  106. StringRef Text = getText(E, Context);
  107. if (Text.empty())
  108. return llvm::None;
  109. if (needParensAfterUnaryOperator(E)) {
  110. return ("&(" + Text + ")").str();
  111. }
  112. return ("&" + Text).str();
  113. }
  114. // Append the appropriate access operation (syntactically) to `E`, assuming `E`
  115. // is a non-pointer value.
  116. static llvm::Optional<std::string>
  117. buildAccessForValue(const Expr &E, const ASTContext &Context) {
  118. if (const auto *Op = llvm::dyn_cast<UnaryOperator>(&E))
  119. if (Op->getOpcode() == UO_Deref) {
  120. // Strip leading '*', add following '->'.
  121. const Expr *SubExpr = Op->getSubExpr()->IgnoreParenImpCasts();
  122. StringRef DerefText = getText(*SubExpr, Context);
  123. if (DerefText.empty())
  124. return llvm::None;
  125. if (needParensBeforeDotOrArrow(*SubExpr))
  126. return ("(" + DerefText + ")->").str();
  127. return (DerefText + "->").str();
  128. }
  129. // Add following '.'.
  130. StringRef Text = getText(E, Context);
  131. if (Text.empty())
  132. return llvm::None;
  133. if (needParensBeforeDotOrArrow(E)) {
  134. return ("(" + Text + ").").str();
  135. }
  136. return (Text + ".").str();
  137. }
  138. // Append the appropriate access operation (syntactically) to `E`, assuming `E`
  139. // is a pointer value.
  140. static llvm::Optional<std::string>
  141. buildAccessForPointer(const Expr &E, const ASTContext &Context) {
  142. if (const auto *Op = llvm::dyn_cast<UnaryOperator>(&E))
  143. if (Op->getOpcode() == UO_AddrOf) {
  144. // Strip leading '&', add following '.'.
  145. const Expr *SubExpr = Op->getSubExpr()->IgnoreParenImpCasts();
  146. StringRef DerefText = getText(*SubExpr, Context);
  147. if (DerefText.empty())
  148. return llvm::None;
  149. if (needParensBeforeDotOrArrow(*SubExpr))
  150. return ("(" + DerefText + ").").str();
  151. return (DerefText + ".").str();
  152. }
  153. // Add following '->'.
  154. StringRef Text = getText(E, Context);
  155. if (Text.empty())
  156. return llvm::None;
  157. if (needParensBeforeDotOrArrow(E))
  158. return ("(" + Text + ")->").str();
  159. return (Text + "->").str();
  160. }
  161. llvm::Optional<std::string> tooling::buildDot(const Expr &E,
  162. const ASTContext &Context) {
  163. return buildAccessForValue(E, Context);
  164. }
  165. llvm::Optional<std::string> tooling::buildArrow(const Expr &E,
  166. const ASTContext &Context) {
  167. return buildAccessForPointer(E, Context);
  168. }
  169. // If `E` is an overloaded-operator call of kind `K` on an object `O`, returns
  170. // `O`. Otherwise, returns `nullptr`.
  171. static const Expr *maybeGetOperatorObjectArg(const Expr &E,
  172. OverloadedOperatorKind K) {
  173. if (const auto *OpCall = dyn_cast<clang::CXXOperatorCallExpr>(&E)) {
  174. if (OpCall->getOperator() == K && OpCall->getNumArgs() == 1)
  175. return OpCall->getArg(0);
  176. }
  177. return nullptr;
  178. }
  179. static bool treatLikePointer(QualType Ty, PLTClass C, ASTContext &Context) {
  180. switch (C) {
  181. case PLTClass::Value:
  182. return false;
  183. case PLTClass::Pointer:
  184. return isKnownPointerLikeType(Ty, Context);
  185. }
  186. llvm_unreachable("Unknown PLTClass enum");
  187. }
  188. // FIXME: move over the other `maybe` functionality from Stencil. Should all be
  189. // in one place.
  190. llvm::Optional<std::string> tooling::buildAccess(const Expr &RawExpression,
  191. ASTContext &Context,
  192. PLTClass Classification) {
  193. if (RawExpression.isImplicitCXXThis())
  194. // Return the empty string, because `None` signifies some sort of failure.
  195. return std::string();
  196. const Expr *E = RawExpression.IgnoreImplicitAsWritten();
  197. if (E->getType()->isAnyPointerType() ||
  198. treatLikePointer(E->getType(), Classification, Context)) {
  199. // Strip off operator-> calls. They can only occur inside an actual arrow
  200. // member access, so we treat them as equivalent to an actual object
  201. // expression.
  202. if (const auto *Obj = maybeGetOperatorObjectArg(*E, clang::OO_Arrow))
  203. E = Obj;
  204. return buildAccessForPointer(*E, Context);
  205. }
  206. if (const auto *Obj = maybeGetOperatorObjectArg(*E, clang::OO_Star)) {
  207. if (treatLikePointer(Obj->getType(), Classification, Context))
  208. return buildAccessForPointer(*Obj, Context);
  209. };
  210. return buildAccessForValue(*E, Context);
  211. }