code_template.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. #pragma once
  3. #include <c10/util/irange.h>
  4. #include <sstream>
  5. #include <string>
  6. #include <unordered_map>
  7. #include <vector>
  8. namespace at::jit {
  9. // A template environment is a mapping from template variable names, e.g.,
  10. // identifier (corresponding to $identifier) to their expansions.
  11. //
  12. // This template environment supports storing strings, numbers and lists
  13. // of strings, and can be chained together (so that lookup proceeds in
  14. // in the top level environment, and then recurses into a parent
  15. // environment if the key is not found.)
  16. struct TemplateEnv {
  17. TemplateEnv() = default;
  18. TemplateEnv(TemplateEnv& parent) : parent(&parent) {}
  19. TemplateEnv(TemplateEnv&&) = delete;
  20. TemplateEnv& operator=(const TemplateEnv& parent) = delete;
  21. TemplateEnv& operator=(TemplateEnv&& parent) = delete;
  22. ~TemplateEnv() = default;
  23. using string_list = std::vector<std::string>;
  24. // Add a string 'v' to the map at key 'k'.
  25. void s(const std::string& k, const std::string& v) {
  26. strings_[k] = v;
  27. lists_.erase(k);
  28. }
  29. // Add a number 'v' to the map at key 'k'
  30. template <typename T>
  31. void d(const std::string& k, const T& v) {
  32. strings_[k] = std::to_string(v);
  33. lists_.erase(k);
  34. }
  35. // Retrieve the string representation of the value stored at 'k' from the map.
  36. // Raises an exception if the key is not found.
  37. const std::string& s(const std::string& k) const {
  38. if (strings_.count(k) == 0) {
  39. if (parent) {
  40. return parent->s(k);
  41. }
  42. notFound(k);
  43. }
  44. return strings_.at(k);
  45. }
  46. // Store a list of strings 'v' in the map at 'k'.
  47. void v(const std::string& k, const string_list& v) {
  48. lists_[k] = v;
  49. strings_.erase(k);
  50. }
  51. // Retrieve a list of strings stored at 'k' from the map.
  52. // Raises an exception if the key is not found.
  53. const string_list& v(const std::string& k) const {
  54. if (lists_.count(k) == 0) {
  55. if (parent) {
  56. return parent->v(k);
  57. }
  58. notFound(k);
  59. }
  60. return lists_.at(k);
  61. }
  62. // Test if a string 'k' is a string (as opposed to a list.)
  63. bool keyIsString(const std::string& k) const {
  64. if (strings_.count(k) > 0)
  65. return true;
  66. if (lists_.count(k) > 0)
  67. return false;
  68. if (parent)
  69. return parent->keyIsString(k);
  70. notFound(k);
  71. }
  72. private:
  73. [[noreturn]] void notFound(const std::string& k) const {
  74. std::stringstream ss;
  75. ss << "key not found: " << k;
  76. throw std::logic_error(ss.str());
  77. }
  78. std::unordered_map<std::string, std::string> strings_;
  79. std::unordered_map<std::string, string_list> lists_;
  80. TemplateEnv* parent{nullptr};
  81. };
  82. /*
  83. # Match $identifier or ${identifier} and replace with the value in env.
  84. # If this identifier is at the beginning of whitespace on a line
  85. # and its value is a list then it is treated as
  86. # block substitution by indenting all lines of all elements.
  87. # If the identifier is on a line starting with non-whitespace and a list
  88. # then it is comma separated. ${,foo} will insert a comma before the list
  89. # if this list is not empty and ${foo,} will insert one after.
  90. */
  91. struct CodeTemplate {
  92. /* implicit */ CodeTemplate(std::string t) : template_text(std::move(t)) {}
  93. std::string format(const TemplateEnv& env) const {
  94. std::stringstream out;
  95. size_t pos = 0;
  96. size_t indent = 0;
  97. bool all_whitespace = true;
  98. while (pos < template_text.size()) {
  99. char c = template_text[pos];
  100. if (c == '$') {
  101. std::stringstream kss;
  102. bool comma_before = false;
  103. bool comma_after = false;
  104. size_t new_pos = parseKey(pos, kss, comma_before, comma_after);
  105. std::string k = kss.str();
  106. bool is_string = env.keyIsString(k);
  107. if (all_whitespace) {
  108. if (is_string)
  109. emitStringWithIndents(out, indent, env.s(k));
  110. else
  111. emitLinesIndented(out, indent, env.v(k));
  112. } else {
  113. if (is_string)
  114. out << env.s(k);
  115. else
  116. emitCommaSeparatedList(out, env.v(k), comma_before, comma_after);
  117. }
  118. all_whitespace = false;
  119. pos = new_pos;
  120. } else {
  121. out << c;
  122. if (!isspace(c))
  123. all_whitespace = false;
  124. indent++;
  125. if (c == '\n') {
  126. indent = 0;
  127. all_whitespace = true;
  128. }
  129. pos++;
  130. }
  131. }
  132. return out.str();
  133. }
  134. private:
  135. using string_list = std::vector<std::string>;
  136. char charAt(size_t p) const {
  137. if (p >= template_text.size())
  138. throw std::logic_error("EOS found in key");
  139. return template_text[p];
  140. }
  141. size_t parseKey(
  142. size_t pos,
  143. std::ostream& k,
  144. bool& comma_before,
  145. bool& comma_after) const {
  146. comma_before = false;
  147. comma_after = false;
  148. pos++;
  149. if (charAt(pos) == '{') {
  150. pos++;
  151. if (charAt(pos) == ',') {
  152. comma_before = true;
  153. pos++;
  154. }
  155. pos = parseIdent(pos, k);
  156. if (charAt(pos) == ',') {
  157. comma_after = true;
  158. pos++;
  159. }
  160. if (charAt(pos) != '}')
  161. throw std::logic_error("missing terminating '}'");
  162. pos++;
  163. return pos;
  164. } else {
  165. return parseIdent(pos, k);
  166. }
  167. }
  168. size_t parseIdent(size_t pos, std::ostream& k) const {
  169. while (pos < template_text.size() &&
  170. (isalnum(template_text[pos]) || template_text[pos] == '_')) {
  171. k << template_text[pos];
  172. pos++;
  173. }
  174. return pos;
  175. }
  176. void emitCommaSeparatedList(
  177. std::ostream& out,
  178. const string_list& strings,
  179. bool comma_before,
  180. bool comma_after) const {
  181. if (comma_before && !strings.empty())
  182. out << ", ";
  183. for (const auto i : c10::irange(strings.size())) {
  184. if (i > 0)
  185. out << ", ";
  186. out << strings[i];
  187. }
  188. if (comma_after && !strings.empty())
  189. out << ", ";
  190. }
  191. // These indentation functions follow the convention that they never emit
  192. // leading or trailing newlines when the input string does not have leading
  193. // or trailing newlines. It's the responsibility of the calling function
  194. // to indent correctly in the context.
  195. void emitIndent(std::ostream& out, size_t indent) const {
  196. for ([[maybe_unused]] const auto i : c10::irange(indent)) {
  197. out << ' ';
  198. }
  199. }
  200. void emitStringWithIndents(
  201. std::ostream& out,
  202. size_t indent,
  203. const std::string& str) const {
  204. for (auto c : str) {
  205. out << c;
  206. if (c == '\n') {
  207. emitIndent(out, indent);
  208. }
  209. }
  210. }
  211. void emitLinesIndented(
  212. std::stringstream& out,
  213. size_t indent,
  214. const string_list& strings) const {
  215. for (const auto i : c10::irange(strings.size())) {
  216. if (i > 0)
  217. emitIndent(out, indent);
  218. emitStringWithIndents(out, indent, strings[i]);
  219. if (i + 1 != strings.size())
  220. out << '\n';
  221. }
  222. }
  223. std::string template_text;
  224. };
  225. static inline std::string format(const std::string& fmt, TemplateEnv& env) {
  226. return CodeTemplate(fmt).format(env);
  227. }
  228. } // namespace at::jit
  229. #else
  230. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  231. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)