Stencil.h 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- Stencil.h - Stencil class ------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file defines the *Stencil* abstraction: a code-generating object,
  16. /// parameterized by named references to (bound) AST nodes. Given a match
  17. /// result, a stencil can be evaluated to a string of source code.
  18. ///
  19. /// A stencil is similar in spirit to a format string: it is composed of a
  20. /// series of raw text strings, references to nodes (the parameters) and helper
  21. /// code-generation operations.
  22. ///
  23. //===----------------------------------------------------------------------===//
  24. #ifndef LLVM_CLANG_TOOLING_TRANSFORMER_STENCIL_H_
  25. #define LLVM_CLANG_TOOLING_TRANSFORMER_STENCIL_H_
  26. #include "clang/AST/ASTContext.h"
  27. #include "clang/AST/ASTTypeTraits.h"
  28. #include "clang/ASTMatchers/ASTMatchFinder.h"
  29. #include "clang/Tooling/Transformer/MatchConsumer.h"
  30. #include "clang/Tooling/Transformer/RangeSelector.h"
  31. #include "llvm/ADT/StringRef.h"
  32. #include "llvm/Support/Error.h"
  33. #include <string>
  34. #include <vector>
  35. namespace clang {
  36. namespace transformer {
  37. using StencilInterface = MatchComputation<std::string>;
  38. /// A sequence of code fragments, references to parameters and code-generation
  39. /// operations that together can be evaluated to (a fragment of) source code or
  40. /// a diagnostic message, given a match result.
  41. ///
  42. /// We use a `shared_ptr` to allow for easy and cheap copying of stencils.
  43. /// Since `StencilInterface` is an immutable interface, the sharing doesn't
  44. /// impose any risks. Otherwise, we would have to add a virtual `copy` method to
  45. /// the API and implement it for all derived classes.
  46. using Stencil = std::shared_ptr<StencilInterface>;
  47. namespace detail {
  48. /// Convenience function to construct a \c Stencil. Overloaded for common cases
  49. /// so that user doesn't need to specify which factory function to use. This
  50. /// pattern gives benefits similar to implicit constructors, while maintaing a
  51. /// higher degree of explicitness.
  52. Stencil makeStencil(llvm::StringRef Text);
  53. Stencil makeStencil(RangeSelector Selector);
  54. inline Stencil makeStencil(Stencil S) { return S; }
  55. } // namespace detail
  56. /// Constructs the string representing the concatenation of the given \p
  57. /// Parts. If only one element is passed in \p Parts, returns that element.
  58. Stencil catVector(std::vector<Stencil> Parts);
  59. /// Concatenates 0+ stencil pieces into a single stencil. Arguments can be raw
  60. /// text, ranges in the matched code (\p RangeSelector) or other `Stencil`s.
  61. template <typename... Ts> Stencil cat(Ts &&... Parts) {
  62. return catVector({detail::makeStencil(std::forward<Ts>(Parts))...});
  63. }
  64. //
  65. // Functions for conveniently building stencils.
  66. //
  67. /// Generates the source of the expression bound to \p Id, wrapping it in
  68. /// parentheses if it may parse differently depending on context. For example, a
  69. /// binary operation is always wrapped, while a variable reference is never
  70. /// wrapped.
  71. Stencil expression(llvm::StringRef Id);
  72. /// Constructs an idiomatic dereferencing of the expression bound to \p ExprId.
  73. /// \p ExprId is wrapped in parentheses, if needed.
  74. Stencil deref(llvm::StringRef ExprId);
  75. /// If \p ExprId is of pointer type, constructs an idiomatic dereferencing of
  76. /// the expression bound to \p ExprId, including wrapping it in parentheses, if
  77. /// needed. Otherwise, generates the original expression source.
  78. Stencil maybeDeref(llvm::StringRef ExprId);
  79. /// Constructs an expression that idiomatically takes the address of the
  80. /// expression bound to \p ExprId. \p ExprId is wrapped in parentheses, if
  81. /// needed.
  82. Stencil addressOf(llvm::StringRef ExprId);
  83. /// If \p ExprId is not a pointer type, constructs an expression that
  84. /// idiomatically takes the address of the expression bound to \p ExprId,
  85. /// including wrapping \p ExprId in parentheses, if needed. Otherwise, generates
  86. /// the original expression source.
  87. Stencil maybeAddressOf(llvm::StringRef ExprId);
  88. /// Constructs a `MemberExpr` that accesses the named member (\p Member) of the
  89. /// object bound to \p BaseId. The access is constructed idiomatically: if \p
  90. /// BaseId is bound to `e` and \p Member identifies member `m`, then returns
  91. /// `e->m`, when e is a pointer, `e2->m` when e = `*e2` and `e.m` otherwise.
  92. /// Additionally, `e` is wrapped in parentheses, if needed.
  93. Stencil access(llvm::StringRef BaseId, Stencil Member);
  94. inline Stencil access(llvm::StringRef BaseId, llvm::StringRef Member) {
  95. return access(BaseId, detail::makeStencil(Member));
  96. }
  97. /// Chooses between the two stencil parts, based on whether \p ID is bound in
  98. /// the match.
  99. Stencil ifBound(llvm::StringRef Id, Stencil TrueStencil, Stencil FalseStencil);
  100. /// Chooses between the two strings, based on whether \p ID is bound in the
  101. /// match.
  102. inline Stencil ifBound(llvm::StringRef Id, llvm::StringRef TrueText,
  103. llvm::StringRef FalseText) {
  104. return ifBound(Id, detail::makeStencil(TrueText),
  105. detail::makeStencil(FalseText));
  106. }
  107. /// Chooses between multiple stencils, based on the presence of bound nodes. \p
  108. /// CaseStencils takes a vector of (ID, \c Stencil) pairs and checks each ID in
  109. /// order to see if it's bound to a node. If so, the associated \c Stencil is
  110. /// run and all other cases are ignored. An optional \p DefaultStencil can be
  111. /// provided to be run if all cases are exhausted beacause none of the provided
  112. /// IDs are bound. If no default case is provided and all cases are exhausted,
  113. /// the stencil will fail with error `llvm::errc::result_out_of_range`.
  114. ///
  115. /// For example, say one matches a statement's type with:
  116. /// anyOf(
  117. /// qualType(isInteger()).bind("int"),
  118. /// qualType(realFloatingPointType()).bind("float"),
  119. /// qualType(isAnyCharacter()).bind("char"),
  120. /// booleanType().bind("bool"))
  121. ///
  122. /// Then, one can decide in a stencil how to construct a literal.
  123. /// cat("a = ",
  124. /// selectBound(
  125. /// {{"int", cat("0")},
  126. /// {"float", cat("0.0")},
  127. /// {"char", cat("'\\0'")},
  128. /// {"bool", cat("false")}}))
  129. ///
  130. /// In addition, one could supply a default case for all other types:
  131. /// selectBound(
  132. /// {{"int", cat("0")},
  133. /// ...
  134. /// {"bool", cat("false")}},
  135. /// cat("{}"))
  136. Stencil selectBound(std::vector<std::pair<std::string, Stencil>> CaseStencils,
  137. Stencil DefaultStencil = nullptr);
  138. /// Wraps a \c MatchConsumer in a \c Stencil, so that it can be used in a \c
  139. /// Stencil. This supports user-defined extensions to the \c Stencil language.
  140. Stencil run(MatchConsumer<std::string> C);
  141. /// Produces a human-readable rendering of the node bound to `Id`, suitable for
  142. /// diagnostics and debugging. This operator can be applied to any node, but is
  143. /// targeted at those whose source cannot be printed directly, including:
  144. ///
  145. /// * Types. represented based on their structure. Note that namespace
  146. /// qualifiers are always printed, with the anonymous namespace represented
  147. /// explicitly. No desugaring or canonicalization is applied.
  148. Stencil describe(llvm::StringRef Id);
  149. /// For debug use only; semantics are not guaranteed.
  150. ///
  151. /// \returns the string resulting from calling the node's print() method.
  152. Stencil dPrint(llvm::StringRef Id);
  153. } // namespace transformer
  154. } // namespace clang
  155. #endif // LLVM_CLANG_TOOLING_TRANSFORMER_STENCIL_H_
  156. #ifdef __GNUC__
  157. #pragma GCC diagnostic pop
  158. #endif