extract.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include <tuple>
  5. #include <typeinfo>
  6. #include <utility>
  7. #include "common/error.h"
  8. #include "common/struct_reflection.h"
  9. #include "toolchain/parse/tree.h"
  10. #include "toolchain/parse/typed_nodes.h"
  11. namespace Carbon::Parse {
  12. // A trait type that should be specialized by types that can be extracted
  13. // from a parse tree. A specialization should provide the following API:
  14. //
  15. // ```cpp
  16. // template<>
  17. // struct Extractable<T> {
  18. // // Extract a value of this type from the sequence of nodes starting at
  19. // // `it`, and increment `it` past this type. Returns `std::nullopt` if
  20. // // the tree is malformed. If `trace != nullptr`, writes what actions
  21. // // were taken to `*trace`.
  22. // static auto Extract(Tree* tree, Tree::SiblingIterator& it,
  23. // Tree::SiblingIterator end,
  24. // ErrorBuilder* trace) -> std::optional<T>;
  25. // };
  26. // ```
  27. //
  28. // Note that `Tree::SiblingIterator`s iterate in reverse order through the
  29. // children of a node.
  30. //
  31. // This class is only in this file.
  32. template <typename T>
  33. struct Extractable;
  34. // Extract a `NodeId` as a single child.
  35. template <>
  36. struct Extractable<NodeId> {
  37. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  38. Tree::SiblingIterator end, ErrorBuilder* trace)
  39. -> std::optional<NodeId> {
  40. if (it == end) {
  41. if (trace) {
  42. *trace << "NodeId error: no more children\n";
  43. }
  44. return std::nullopt;
  45. }
  46. if (trace) {
  47. *trace << "NodeId: " << tree->node_kind(*it) << " consumed\n";
  48. }
  49. return NodeId(*it++);
  50. }
  51. };
  52. // Extract a `FooId`, which is the same as `NodeIdForKind<NodeKind::Foo>`,
  53. // as a single required child.
  54. template <const NodeKind& Kind>
  55. struct Extractable<NodeIdForKind<Kind>> {
  56. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  57. Tree::SiblingIterator end, ErrorBuilder* trace)
  58. -> std::optional<NodeIdForKind<Kind>> {
  59. if (it == end || tree->node_kind(*it) != Kind) {
  60. if (trace) {
  61. if (it == end) {
  62. *trace << "NodeIdForKind error: no more children, expected " << Kind
  63. << "\n";
  64. } else {
  65. *trace << "NodeIdForKind error: wrong kind " << tree->node_kind(*it)
  66. << ", expected " << Kind << "\n";
  67. }
  68. }
  69. return std::nullopt;
  70. }
  71. if (trace) {
  72. *trace << "NodeIdForKind: " << Kind << " consumed\n";
  73. }
  74. return NodeIdForKind<Kind>(*it++);
  75. }
  76. };
  77. // Extract a `NodeIdInCategory<Category>` as a single child.
  78. template <NodeCategory Category>
  79. struct Extractable<NodeIdInCategory<Category>> {
  80. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  81. Tree::SiblingIterator end, ErrorBuilder* trace)
  82. -> std::optional<NodeIdInCategory<Category>> {
  83. if (it == end || !(tree->node_kind(*it).category() & Category)) {
  84. if (trace) {
  85. *trace << "NodeIdInCategory " << Category << " error: ";
  86. if (it == end) {
  87. *trace << "no more children\n";
  88. } else {
  89. *trace << "kind " << tree->node_kind(*it) << " doesn't match\n";
  90. }
  91. }
  92. return std::nullopt;
  93. }
  94. if (trace) {
  95. *trace << "NodeIdInCategory " << Category << ": kind "
  96. << tree->node_kind(*it) << " consumed\n";
  97. }
  98. return NodeIdInCategory<Category>(*it++);
  99. }
  100. };
  101. // Extract a `NodeIdOneOf<T, U>` as a single required child.
  102. template <typename T, typename U>
  103. struct Extractable<NodeIdOneOf<T, U>> {
  104. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  105. Tree::SiblingIterator end, ErrorBuilder* trace)
  106. -> std::optional<NodeIdOneOf<T, U>> {
  107. auto kind = tree->node_kind(*it);
  108. if (it == end || (kind != T::Kind && kind != U::Kind)) {
  109. if (trace) {
  110. if (it == end) {
  111. *trace << "NodeIdOneOf error: no more children, expected " << T::Kind
  112. << " or " << U::Kind << "\n";
  113. } else {
  114. *trace << "NodeIdOneOf error: wrong kind " << tree->node_kind(*it)
  115. << ", expected " << T::Kind << " or " << U::Kind << "\n";
  116. }
  117. }
  118. return std::nullopt;
  119. }
  120. if (trace) {
  121. *trace << "NodeIdOneOf " << T::Kind << " or " << U::Kind << ": "
  122. << tree->node_kind(*it) << " consumed\n";
  123. }
  124. return NodeIdOneOf<T, U>(*it++);
  125. }
  126. };
  127. // Extract a `NodeIdNot<T>` as a single required child.
  128. template <typename T>
  129. struct Extractable<NodeIdNot<T>> {
  130. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  131. Tree::SiblingIterator end, ErrorBuilder* trace)
  132. -> std::optional<NodeIdNot<T>> {
  133. if (it == end || tree->node_kind(*it) == T::Kind) {
  134. if (trace) {
  135. if (it == end) {
  136. *trace << "NodeIdNot " << T::Kind << " error: no more children\n";
  137. } else {
  138. *trace << "NodeIdNot error: unexpected " << T::Kind << "\n";
  139. }
  140. }
  141. return std::nullopt;
  142. }
  143. if (trace) {
  144. *trace << "NodeIdNot " << T::Kind << ": " << tree->node_kind(*it)
  145. << " consumed\n";
  146. }
  147. return NodeIdNot<T>(*it++);
  148. }
  149. };
  150. // Extract an `llvm::SmallVector<T>` by extracting `T`s until we can't.
  151. template <typename T>
  152. struct Extractable<llvm::SmallVector<T>> {
  153. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  154. Tree::SiblingIterator end, ErrorBuilder* trace)
  155. -> std::optional<llvm::SmallVector<T>> {
  156. if (trace) {
  157. *trace << "Vector: begin\n";
  158. }
  159. llvm::SmallVector<T> result;
  160. while (it != end) {
  161. auto old_it = it;
  162. auto item = Extractable<T>::Extract(tree, it, end, trace);
  163. if (!item.has_value()) {
  164. it = old_it;
  165. break;
  166. }
  167. result.push_back(*item);
  168. }
  169. std::reverse(result.begin(), result.end());
  170. if (trace) {
  171. *trace << "Vector: end\n";
  172. }
  173. return result;
  174. }
  175. };
  176. // Extract an `optional<T>` from a list of child nodes by attempting to extract
  177. // a `T`, and extracting nothing if that fails.
  178. template <typename T>
  179. struct Extractable<std::optional<T>> {
  180. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  181. Tree::SiblingIterator end, ErrorBuilder* trace)
  182. -> std::optional<std::optional<T>> {
  183. if (trace) {
  184. *trace << "Optional " << typeid(T).name() << ": begin\n";
  185. }
  186. auto old_it = it;
  187. std::optional<T> value = Extractable<T>::Extract(tree, it, end, trace);
  188. if (value) {
  189. if (trace) {
  190. *trace << "Optional " << typeid(T).name() << ": found\n";
  191. }
  192. return value;
  193. }
  194. if (trace) {
  195. *trace << "Optional " << typeid(T).name() << ": missing\n";
  196. }
  197. it = old_it;
  198. return value;
  199. }
  200. };
  201. // Extract a `tuple<T...>` from a list of child nodes by extracting each `T` in
  202. // reverse order.
  203. template <typename... T>
  204. struct Extractable<std::tuple<T...>> {
  205. template <std::size_t... Index>
  206. static auto ExtractImpl(const Tree* tree, Tree::SiblingIterator& it,
  207. Tree::SiblingIterator end, ErrorBuilder* trace,
  208. std::index_sequence<Index...>)
  209. -> std::optional<std::tuple<T...>> {
  210. std::tuple<std::optional<T>...> fields;
  211. if (trace) {
  212. *trace << sizeof...(T) << "-tuple: begin\n";
  213. }
  214. // Use a fold over the `=` operator to parse fields from right to left.
  215. [[maybe_unused]] int unused;
  216. bool ok = true;
  217. static_cast<void>(
  218. ((ok && (ok = (std::get<Index>(fields) =
  219. Extractable<T>::Extract(tree, it, end, trace))
  220. .has_value()),
  221. unused) = ... = 0));
  222. if (!ok) {
  223. if (trace) {
  224. *trace << sizeof...(T) << "-tuple: error\n";
  225. }
  226. return std::nullopt;
  227. }
  228. if (trace) {
  229. *trace << sizeof...(T) << "-tuple: success\n";
  230. }
  231. return std::tuple<T...>{std::move(std::get<Index>(fields).value())...};
  232. }
  233. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  234. Tree::SiblingIterator end, ErrorBuilder* trace)
  235. -> std::optional<std::tuple<T...>> {
  236. return ExtractImpl(tree, it, end, trace,
  237. std::make_index_sequence<sizeof...(T)>());
  238. }
  239. };
  240. // Extract the fields of a simple aggregate type.
  241. template <typename T>
  242. struct Extractable {
  243. static_assert(std::is_aggregate_v<T>, "Unsupported child type");
  244. static auto ExtractImpl(const Tree* tree, Tree::SiblingIterator& it,
  245. Tree::SiblingIterator end, ErrorBuilder* trace)
  246. -> std::optional<T> {
  247. if (trace) {
  248. *trace << "Aggregate " << typeid(T).name() << ": begin\n";
  249. }
  250. // Extract the corresponding tuple type.
  251. using TupleType = decltype(StructReflection::AsTuple(std::declval<T>()));
  252. auto tuple = Extractable<TupleType>::Extract(tree, it, end, trace);
  253. if (!tuple.has_value()) {
  254. if (trace) {
  255. *trace << "Aggregate " << typeid(T).name() << ": error\n";
  256. }
  257. return std::nullopt;
  258. }
  259. if (trace) {
  260. *trace << "Aggregate " << typeid(T).name() << ": success\n";
  261. }
  262. // Convert the tuple to the struct type.
  263. return std::apply(
  264. [](auto&&... value) {
  265. return T{std::forward<decltype(value)>(value)...};
  266. },
  267. *tuple);
  268. }
  269. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  270. Tree::SiblingIterator end, ErrorBuilder* trace)
  271. -> std::optional<T> {
  272. static_assert(!HasKindMember<T>, "Missing Id suffix");
  273. return ExtractImpl(tree, it, end, trace);
  274. }
  275. };
  276. template <typename T>
  277. auto Tree::TryExtractNodeFromChildren(
  278. llvm::iterator_range<Tree::SiblingIterator> children,
  279. ErrorBuilder* trace) const -> std::optional<T> {
  280. auto it = children.begin();
  281. auto result = Extractable<T>::ExtractImpl(this, it, children.end(), trace);
  282. if (it != children.end()) {
  283. if (trace) {
  284. *trace << "Error: " << node_kind(*it) << " node left unconsumed.";
  285. }
  286. return std::nullopt;
  287. }
  288. return result;
  289. }
  290. // Manually instantiate Tree::TryExtractNodeFromChildren
  291. #define CARBON_PARSE_NODE_KIND(KindName) \
  292. template auto Tree::TryExtractNodeFromChildren<KindName>( \
  293. llvm::iterator_range<Tree::SiblingIterator> children, \
  294. ErrorBuilder * trace) const -> std::optional<KindName>;
  295. // Also instantiate for `File`, even though it isn't a parse node.
  296. CARBON_PARSE_NODE_KIND(File)
  297. #include "toolchain/parse/node_kind.def"
  298. auto Tree::ExtractFile() const -> File {
  299. return ExtractNodeFromChildren<File>(roots());
  300. }
  301. } // namespace Carbon::Parse