extract.cpp 11 KB

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