extract.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 *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 NodeIdOneOfAccept(std::initializer_list<NodeKind> kinds,
  122. const Tree* tree, const Tree::SiblingIterator& it,
  123. Tree::SiblingIterator end, ErrorBuilder* trace)
  124. -> bool {
  125. auto trace_kinds = [&] {
  126. llvm::ListSeparator sep(" or ");
  127. for (auto kind : kinds) {
  128. *trace << sep << kind;
  129. }
  130. };
  131. auto kind = tree->node_kind(*it);
  132. if (it == end || std::find(kinds.begin(), kinds.end(), kind) == kinds.end()) {
  133. if (trace) {
  134. if (it == end) {
  135. *trace << "NodeIdOneOf error: no more children, expected ";
  136. trace_kinds();
  137. *trace << "\n";
  138. } else {
  139. *trace << "NodeIdOneOf error: wrong kind " << tree->node_kind(*it)
  140. << ", expected ";
  141. trace_kinds();
  142. *trace << "\n";
  143. }
  144. }
  145. return false;
  146. }
  147. if (trace) {
  148. *trace << "NodeIdOneOf ";
  149. trace_kinds();
  150. *trace << ": " << tree->node_kind(*it) << " consumed\n";
  151. }
  152. return true;
  153. }
  154. // Extract a `NodeIdOneOf<T...>` as a single required child.
  155. template <typename... T>
  156. struct Extractable<NodeIdOneOf<T...>> {
  157. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  158. Tree::SiblingIterator end, ErrorBuilder* trace)
  159. -> std::optional<NodeIdOneOf<T...>> {
  160. if (NodeIdOneOfAccept({T::Kind...}, tree, it, end, trace)) {
  161. return NodeIdOneOf<T...>(*it++);
  162. } else {
  163. return std::nullopt;
  164. }
  165. }
  166. };
  167. // Extract a `NodeIdNot<T>` as a single required child.
  168. // Note: this is only instantiated once, so no need to create a helper function.
  169. template <typename T>
  170. struct Extractable<NodeIdNot<T>> {
  171. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  172. Tree::SiblingIterator end, ErrorBuilder* trace)
  173. -> std::optional<NodeIdNot<T>> {
  174. if (it == end || tree->node_kind(*it) == T::Kind) {
  175. if (trace) {
  176. if (it == end) {
  177. *trace << "NodeIdNot " << T::Kind << " error: no more children\n";
  178. } else {
  179. *trace << "NodeIdNot error: unexpected " << T::Kind << "\n";
  180. }
  181. }
  182. return std::nullopt;
  183. }
  184. if (trace) {
  185. *trace << "NodeIdNot " << T::Kind << ": " << tree->node_kind(*it)
  186. << " consumed\n";
  187. }
  188. return NodeIdNot<T>(*it++);
  189. }
  190. };
  191. // Extract an `llvm::SmallVector<T>` by extracting `T`s until we can't.
  192. template <typename T>
  193. struct Extractable<llvm::SmallVector<T>> {
  194. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  195. Tree::SiblingIterator end, ErrorBuilder* trace)
  196. -> std::optional<llvm::SmallVector<T>> {
  197. if (trace) {
  198. *trace << "Vector: begin\n";
  199. }
  200. llvm::SmallVector<T> result;
  201. while (it != end) {
  202. auto old_it = it;
  203. auto item = Extractable<T>::Extract(tree, it, end, trace);
  204. if (!item.has_value()) {
  205. it = old_it;
  206. break;
  207. }
  208. result.push_back(*item);
  209. }
  210. std::reverse(result.begin(), result.end());
  211. if (trace) {
  212. *trace << "Vector: end\n";
  213. }
  214. return result;
  215. }
  216. };
  217. // Extract an `optional<T>` from a list of child nodes by attempting to extract
  218. // a `T`, and extracting nothing if that fails.
  219. template <typename T>
  220. struct Extractable<std::optional<T>> {
  221. static auto Extract(const Tree* tree, Tree::SiblingIterator& it,
  222. Tree::SiblingIterator end, ErrorBuilder* trace)
  223. -> std::optional<std::optional<T>> {
  224. if (trace) {
  225. *trace << "Optional " << typeid(T).name() << ": begin\n";
  226. }
  227. auto old_it = it;
  228. std::optional<T> value = Extractable<T>::Extract(tree, it, end, trace);
  229. if (value) {
  230. if (trace) {
  231. *trace << "Optional " << typeid(T).name() << ": found\n";
  232. }
  233. return value;
  234. }
  235. if (trace) {
  236. *trace << "Optional " << typeid(T).name() << ": missing\n";
  237. }
  238. it = old_it;
  239. return value;
  240. }
  241. };
  242. template <typename T, typename... U, std::size_t... Index>
  243. static auto ExtractTupleLikeType(const Tree* tree, Tree::SiblingIterator& it,
  244. Tree::SiblingIterator end, ErrorBuilder* trace,
  245. std::index_sequence<Index...> /*indices*/,
  246. std::tuple<U...>* /*type*/)
  247. -> std::optional<T> {
  248. std::tuple<std::optional<U>...> fields;
  249. if (trace) {
  250. *trace << "Aggregate " << typeid(T).name() << ": begin\n";
  251. }
  252. // Use a fold over the `=` operator to parse fields from right to left.
  253. [[maybe_unused]] int unused;
  254. bool ok = true;
  255. static_cast<void>(
  256. ((ok && (ok = (std::get<Index>(fields) =
  257. Extractable<U>::Extract(tree, it, end, trace))
  258. .has_value()),
  259. unused) = ... = 0));
  260. if (!ok) {
  261. if (trace) {
  262. *trace << "Aggregate " << typeid(T).name() << ": error\n";
  263. }
  264. return std::nullopt;
  265. }
  266. if (trace) {
  267. *trace << "Aggregate " << typeid(T).name() << ": success\n";
  268. }
  269. return T{std::move(std::get<Index>(fields).value())...};
  270. }
  271. // Extract the fields of a simple aggregate type.
  272. template <typename T>
  273. struct Extractable {
  274. static_assert(std::is_aggregate_v<T>, "Unsupported child type");
  275. static auto ExtractImpl(const Tree* tree, Tree::SiblingIterator& it,
  276. Tree::SiblingIterator end, ErrorBuilder* trace)
  277. -> std::optional<T> {
  278. // Compute the corresponding tuple type.
  279. using TupleType = decltype(StructReflection::AsTuple(std::declval<T>()));
  280. return ExtractTupleLikeType<T>(
  281. tree, it, end, trace,
  282. std::make_index_sequence<std::tuple_size_v<TupleType>>(),
  283. static_cast<TupleType*>(nullptr));
  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