extract.cpp 11 KB

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