extract.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. static auto NodeIdForKindAccept(const NodeKind& kind, const Tree* tree,
  53. const Tree::SiblingIterator& it,
  54. Tree::SiblingIterator end, ErrorBuilder* trace)
  55. -> bool {
  56. if (it == end || tree->node_kind(*it) != kind) {
  57. if (trace) {
  58. if (it == end) {
  59. *trace << "NodeIdForKind error: no more children, expected " << kind
  60. << "\n";
  61. } else {
  62. *trace << "NodeIdForKind error: wrong kind " << tree->node_kind(*it)
  63. << ", expected " << kind << "\n";
  64. }
  65. }
  66. return false;
  67. }
  68. if (trace) {
  69. *trace << "NodeIdForKind: " << kind << " consumed\n";
  70. }
  71. return true;
  72. }
  73. // Extract a `FooId`, which is the same as `NodeIdForKind<NodeKind::Foo>`,
  74. // as a single required child.
  75. template <const NodeKind& Kind>
  76. struct Extractable<NodeIdForKind<Kind>> {
  77. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  78. Tree::SiblingIterator end, ErrorBuilder* trace)
  79. -> std::optional<NodeIdForKind<Kind>> {
  80. if (NodeIdForKindAccept(Kind, tree, it, end, trace)) {
  81. return NodeIdForKind<Kind>(*it++);
  82. } else {
  83. return std::nullopt;
  84. }
  85. }
  86. };
  87. static auto NodeIdInCategoryAccept(NodeCategory category, const Tree* tree,
  88. const Tree::SiblingIterator& it,
  89. Tree::SiblingIterator end,
  90. ErrorBuilder* trace) -> bool {
  91. if (it == end || !(tree->node_kind(*it).category() & category)) {
  92. if (trace) {
  93. *trace << "NodeIdInCategory " << category << " error: ";
  94. if (it == end) {
  95. *trace << "no more children\n";
  96. } else {
  97. *trace << "kind " << tree->node_kind(*it) << " doesn't match\n";
  98. }
  99. }
  100. return false;
  101. }
  102. if (trace) {
  103. *trace << "NodeIdInCategory " << category << ": kind "
  104. << tree->node_kind(*it) << " consumed\n";
  105. }
  106. return true;
  107. }
  108. // Extract a `NodeIdInCategory<Category>` as a single child.
  109. template <NodeCategory Category>
  110. struct Extractable<NodeIdInCategory<Category>> {
  111. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  112. Tree::SiblingIterator end, ErrorBuilder* trace)
  113. -> std::optional<NodeIdInCategory<Category>> {
  114. if (NodeIdInCategoryAccept(Category, tree, it, end, trace)) {
  115. return NodeIdInCategory<Category>(*it++);
  116. } else {
  117. return std::nullopt;
  118. }
  119. }
  120. };
  121. static auto NodeIdForKindAccept(NodeKind kind1, NodeKind kind2,
  122. const Tree* tree,
  123. const Tree::SiblingIterator& it,
  124. Tree::SiblingIterator end, ErrorBuilder* trace)
  125. -> bool {
  126. auto kind = tree->node_kind(*it);
  127. if (it == end || (kind != kind1 && kind != kind2)) {
  128. if (trace) {
  129. if (it == end) {
  130. *trace << "NodeIdOneOf error: no more children, expected " << kind1
  131. << " or " << kind2 << "\n";
  132. } else {
  133. *trace << "NodeIdOneOf error: wrong kind " << tree->node_kind(*it)
  134. << ", expected " << kind1 << " or " << kind2 << "\n";
  135. }
  136. }
  137. return false;
  138. }
  139. if (trace) {
  140. *trace << "NodeIdOneOf " << kind1 << " or " << kind2 << ": "
  141. << tree->node_kind(*it) << " consumed\n";
  142. }
  143. return true;
  144. }
  145. // Extract a `NodeIdOneOf<T, U>` as a single required child.
  146. template <typename T, typename U>
  147. struct Extractable<NodeIdOneOf<T, U>> {
  148. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  149. Tree::SiblingIterator end, ErrorBuilder* trace)
  150. -> std::optional<NodeIdOneOf<T, U>> {
  151. if (NodeIdForKindAccept(T::Kind, U::Kind, tree, it, end, trace)) {
  152. return NodeIdOneOf<T, U>(*it++);
  153. } else {
  154. return std::nullopt;
  155. }
  156. }
  157. };
  158. // Extract a `NodeIdNot<T>` as a single required child.
  159. // Note: this is only instantiated once, so no need to create a helper function.
  160. template <typename T>
  161. struct Extractable<NodeIdNot<T>> {
  162. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  163. Tree::SiblingIterator end, ErrorBuilder* trace)
  164. -> std::optional<NodeIdNot<T>> {
  165. if (it == end || tree->node_kind(*it) == T::Kind) {
  166. if (trace) {
  167. if (it == end) {
  168. *trace << "NodeIdNot " << T::Kind << " error: no more children\n";
  169. } else {
  170. *trace << "NodeIdNot error: unexpected " << T::Kind << "\n";
  171. }
  172. }
  173. return std::nullopt;
  174. }
  175. if (trace) {
  176. *trace << "NodeIdNot " << T::Kind << ": " << tree->node_kind(*it)
  177. << " consumed\n";
  178. }
  179. return NodeIdNot<T>(*it++);
  180. }
  181. };
  182. // Extract an `llvm::SmallVector<T>` by extracting `T`s until we can't.
  183. template <typename T>
  184. struct Extractable<llvm::SmallVector<T>> {
  185. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  186. Tree::SiblingIterator end, ErrorBuilder* trace)
  187. -> std::optional<llvm::SmallVector<T>> {
  188. if (trace) {
  189. *trace << "Vector: begin\n";
  190. }
  191. llvm::SmallVector<T> result;
  192. while (it != end) {
  193. auto old_it = it;
  194. auto item = Extractable<T>::Extract(tree, it, end, trace);
  195. if (!item.has_value()) {
  196. it = old_it;
  197. break;
  198. }
  199. result.push_back(*item);
  200. }
  201. std::reverse(result.begin(), result.end());
  202. if (trace) {
  203. *trace << "Vector: end\n";
  204. }
  205. return result;
  206. }
  207. };
  208. // Extract an `optional<T>` from a list of child nodes by attempting to extract
  209. // a `T`, and extracting nothing if that fails.
  210. template <typename T>
  211. struct Extractable<std::optional<T>> {
  212. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  213. Tree::SiblingIterator end, ErrorBuilder* trace)
  214. -> std::optional<std::optional<T>> {
  215. if (trace) {
  216. *trace << "Optional " << typeid(T).name() << ": begin\n";
  217. }
  218. auto old_it = it;
  219. std::optional<T> value = Extractable<T>::Extract(tree, it, end, trace);
  220. if (value) {
  221. if (trace) {
  222. *trace << "Optional " << typeid(T).name() << ": found\n";
  223. }
  224. return value;
  225. }
  226. if (trace) {
  227. *trace << "Optional " << typeid(T).name() << ": missing\n";
  228. }
  229. it = old_it;
  230. return value;
  231. }
  232. };
  233. // Extract a `tuple<T...>` from a list of child nodes by extracting each `T` in
  234. // reverse order.
  235. template <typename... T>
  236. struct Extractable<std::tuple<T...>> {
  237. template <std::size_t... Index>
  238. static auto ExtractImpl(const Tree* tree, Tree::SiblingIterator& it,
  239. Tree::SiblingIterator end, ErrorBuilder* trace,
  240. std::index_sequence<Index...>)
  241. -> std::optional<std::tuple<T...>> {
  242. std::tuple<std::optional<T>...> fields;
  243. if (trace) {
  244. *trace << sizeof...(T) << "-tuple: begin\n";
  245. }
  246. // Use a fold over the `=` operator to parse fields from right to left.
  247. [[maybe_unused]] int unused;
  248. bool ok = true;
  249. static_cast<void>(
  250. ((ok && (ok = (std::get<Index>(fields) =
  251. Extractable<T>::Extract(tree, it, end, trace))
  252. .has_value()),
  253. unused) = ... = 0));
  254. if (!ok) {
  255. if (trace) {
  256. *trace << sizeof...(T) << "-tuple: error\n";
  257. }
  258. return std::nullopt;
  259. }
  260. if (trace) {
  261. *trace << sizeof...(T) << "-tuple: success\n";
  262. }
  263. return std::tuple<T...>{std::move(std::get<Index>(fields).value())...};
  264. }
  265. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  266. Tree::SiblingIterator end, ErrorBuilder* trace)
  267. -> std::optional<std::tuple<T...>> {
  268. return ExtractImpl(tree, it, end, trace,
  269. std::make_index_sequence<sizeof...(T)>());
  270. }
  271. };
  272. // Extract the fields of a simple aggregate type.
  273. template <typename T>
  274. struct Extractable {
  275. static_assert(std::is_aggregate_v<T>, "Unsupported child type");
  276. static auto ExtractImpl(const Tree* tree, Tree::SiblingIterator& it,
  277. Tree::SiblingIterator end, ErrorBuilder* trace)
  278. -> std::optional<T> {
  279. if (trace) {
  280. *trace << "Aggregate " << typeid(T).name() << ": begin\n";
  281. }
  282. // Extract the corresponding tuple type.
  283. using TupleType = decltype(StructReflection::AsTuple(std::declval<T>()));
  284. auto tuple = Extractable<TupleType>::Extract(tree, it, end, trace);
  285. if (!tuple.has_value()) {
  286. if (trace) {
  287. *trace << "Aggregate " << typeid(T).name() << ": error\n";
  288. }
  289. return std::nullopt;
  290. }
  291. if (trace) {
  292. *trace << "Aggregate " << typeid(T).name() << ": success\n";
  293. }
  294. // Convert the tuple to the struct type.
  295. return std::apply(
  296. [](auto&&... value) {
  297. return T{std::forward<decltype(value)>(value)...};
  298. },
  299. *tuple);
  300. }
  301. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  302. Tree::SiblingIterator end, ErrorBuilder* trace)
  303. -> std::optional<T> {
  304. static_assert(!HasKindMember<T>, "Missing Id suffix");
  305. return ExtractImpl(tree, it, end, trace);
  306. }
  307. };
  308. template <typename T>
  309. auto Tree::TryExtractNodeFromChildren(
  310. llvm::iterator_range<Tree::SiblingIterator> children,
  311. ErrorBuilder* trace) const -> std::optional<T> {
  312. auto it = children.begin();
  313. auto result = Extractable<T>::ExtractImpl(this, it, children.end(), trace);
  314. if (it != children.end()) {
  315. if (trace) {
  316. *trace << "Error: " << node_kind(*it) << " node left unconsumed.";
  317. }
  318. return std::nullopt;
  319. }
  320. return result;
  321. }
  322. // Manually instantiate Tree::TryExtractNodeFromChildren
  323. #define CARBON_PARSE_NODE_KIND(KindName) \
  324. template auto Tree::TryExtractNodeFromChildren<KindName>( \
  325. llvm::iterator_range<Tree::SiblingIterator> children, \
  326. ErrorBuilder * trace) const -> std::optional<KindName>;
  327. // Also instantiate for `File`, even though it isn't a parse node.
  328. CARBON_PARSE_NODE_KIND(File)
  329. #include "toolchain/parse/node_kind.def"
  330. auto Tree::ExtractFile() const -> File {
  331. return ExtractNodeFromChildren<File>(roots());
  332. }
  333. } // namespace Carbon::Parse