extract.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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/tree_and_subtrees.h"
  11. #include "toolchain/parse/typed_nodes.h"
  12. namespace Carbon::Parse {
  13. namespace {
  14. // Implementation of the process of extracting a typed node structure from the
  15. // parse tree. The extraction process uses the class `Extractable<T>`, defined
  16. // below, to extract individual fields of type `T`.
  17. class NodeExtractor {
  18. public:
  19. struct CheckpointState {
  20. TreeAndSubtrees::SiblingIterator it;
  21. };
  22. NodeExtractor(const TreeAndSubtrees* tree, const Lex::TokenizedBuffer* tokens,
  23. ErrorBuilder* trace, NodeId node_id,
  24. llvm::iterator_range<TreeAndSubtrees::SiblingIterator> children)
  25. : tree_(tree),
  26. tokens_(tokens),
  27. trace_(trace),
  28. node_id_(node_id),
  29. it_(children.begin()),
  30. end_(children.end()) {}
  31. auto at_end() const -> bool { return it_ == end_; }
  32. auto kind() const -> NodeKind { return tree_->tree().node_kind(*it_); }
  33. auto has_token() const -> bool { return node_id_.is_valid(); }
  34. auto token() const -> Lex::TokenIndex {
  35. return tree_->tree().node_token(node_id_);
  36. }
  37. auto token_kind() const -> Lex::TokenKind {
  38. return tokens_->GetKind(token());
  39. }
  40. auto trace() const -> ErrorBuilder* { return trace_; }
  41. // Saves a checkpoint of our current position so we can return later if
  42. // extraction of a child node fails.
  43. auto Checkpoint() const -> CheckpointState { return {.it = it_}; }
  44. auto RestoreCheckpoint(CheckpointState checkpoint) { it_ = checkpoint.it; }
  45. // Determines whether the current position matches the specified node kind. If
  46. // not, produces a suitable trace message.
  47. auto MatchesNodeIdForKind(NodeKind kind) const -> bool;
  48. // Determines whether the current position matches the specified node
  49. // category. If not, produces a suitable trace message.
  50. auto MatchesNodeIdInCategory(NodeCategory category) const -> bool;
  51. // Determines whether the current position matches any of the specified node
  52. // kinds. If not, produces a suitable trace message.
  53. auto MatchesNodeIdOneOf(std::initializer_list<NodeKind> kinds) const -> bool;
  54. // Determines whether the token corresponding to the enclosing node is of the
  55. // specified kind. If not, produces a suitable trace message.
  56. auto MatchesTokenKind(Lex::TokenKind expected_kind) const -> bool;
  57. // Extracts the next node from the tree.
  58. auto ExtractNode() -> NodeId { return *it_++; }
  59. // Extracts a tuple-like type `T` by extracting its components and then
  60. // assembling a `T` value.
  61. template <typename T, typename... U, std::size_t... Index>
  62. auto ExtractTupleLikeType(std::index_sequence<Index...> /*indices*/,
  63. std::tuple<U...>* /*type*/) -> std::optional<T>;
  64. private:
  65. const TreeAndSubtrees* tree_;
  66. const Lex::TokenizedBuffer* tokens_;
  67. ErrorBuilder* trace_;
  68. NodeId node_id_;
  69. TreeAndSubtrees::SiblingIterator it_;
  70. TreeAndSubtrees::SiblingIterator end_;
  71. };
  72. } // namespace
  73. namespace {
  74. // A trait type that should be specialized by types that can be extracted
  75. // from a parse tree. A specialization should provide the following API:
  76. //
  77. // ```cpp
  78. // template<>
  79. // struct Extractable<T> {
  80. // // Extract a value of this type from the sequence of nodes starting at
  81. // // `it`, and increment `it` past this type. Returns `std::nullopt` if
  82. // // the tree is malformed. If `trace != nullptr`, writes what actions
  83. // // were taken to `*trace`.
  84. // static auto Extract(NodeExtractor* extractor) -> std::optional<T>;
  85. // };
  86. // ```
  87. //
  88. // Note that `TreeAndSubtrees::SiblingIterator`s iterate in reverse order
  89. // through the children of a node.
  90. //
  91. // This class is only in this file.
  92. template <typename T>
  93. struct Extractable;
  94. } // namespace
  95. // Extract a `NodeId` as a single child.
  96. template <>
  97. struct Extractable<NodeId> {
  98. static auto Extract(NodeExtractor& extractor) -> std::optional<NodeId> {
  99. if (extractor.at_end()) {
  100. if (auto* trace = extractor.trace()) {
  101. *trace << "NodeId error: no more children\n";
  102. }
  103. return std::nullopt;
  104. }
  105. if (auto* trace = extractor.trace()) {
  106. *trace << "NodeId: " << extractor.kind() << " consumed\n";
  107. }
  108. return extractor.ExtractNode();
  109. }
  110. };
  111. auto NodeExtractor::MatchesNodeIdForKind(NodeKind expected_kind) const -> bool {
  112. if (at_end() || kind() != expected_kind) {
  113. if (trace_) {
  114. if (at_end()) {
  115. *trace_ << "NodeIdForKind error: no more children, expected "
  116. << expected_kind << "\n";
  117. } else {
  118. *trace_ << "NodeIdForKind error: wrong kind " << kind() << ", expected "
  119. << expected_kind << "\n";
  120. }
  121. }
  122. return false;
  123. }
  124. if (trace_) {
  125. *trace_ << "NodeIdForKind: " << expected_kind << " consumed\n";
  126. }
  127. return true;
  128. }
  129. // Extract a `FooId`, which is the same as `NodeIdForKind<NodeKind::Foo>`,
  130. // as a single required child.
  131. template <const NodeKind& Kind>
  132. struct Extractable<NodeIdForKind<Kind>> {
  133. static auto Extract(NodeExtractor& extractor)
  134. -> std::optional<NodeIdForKind<Kind>> {
  135. if (extractor.MatchesNodeIdForKind(Kind)) {
  136. return NodeIdForKind<Kind>(extractor.ExtractNode());
  137. } else {
  138. return std::nullopt;
  139. }
  140. }
  141. };
  142. auto NodeExtractor::MatchesNodeIdInCategory(NodeCategory category) const
  143. -> bool {
  144. if (at_end() || !kind().category().HasAnyOf(category)) {
  145. if (trace_) {
  146. *trace_ << "NodeIdInCategory " << category << " error: ";
  147. if (at_end()) {
  148. *trace_ << "no more children\n";
  149. } else {
  150. *trace_ << "kind " << kind() << " doesn't match\n";
  151. }
  152. }
  153. return false;
  154. }
  155. if (trace_) {
  156. *trace_ << "NodeIdInCategory " << category << ": kind " << kind()
  157. << " consumed\n";
  158. }
  159. return true;
  160. }
  161. // Extract a `NodeIdInCategory<Category>` as a single child.
  162. template <NodeCategory::RawEnumType Category>
  163. struct Extractable<NodeIdInCategory<Category>> {
  164. static auto Extract(NodeExtractor& extractor)
  165. -> std::optional<NodeIdInCategory<Category>> {
  166. if (extractor.MatchesNodeIdInCategory(Category)) {
  167. return NodeIdInCategory<Category>(extractor.ExtractNode());
  168. } else {
  169. return std::nullopt;
  170. }
  171. }
  172. };
  173. auto NodeExtractor::MatchesNodeIdOneOf(
  174. std::initializer_list<NodeKind> kinds) const -> bool {
  175. auto trace_kinds = [&] {
  176. llvm::ListSeparator sep(" or ");
  177. for (auto kind : kinds) {
  178. *trace_ << sep << kind;
  179. }
  180. };
  181. auto node_kind = kind();
  182. if (at_end() ||
  183. std::find(kinds.begin(), kinds.end(), node_kind) == kinds.end()) {
  184. if (trace_) {
  185. if (at_end()) {
  186. *trace_ << "NodeIdOneOf error: no more children, expected ";
  187. trace_kinds();
  188. *trace_ << "\n";
  189. } else {
  190. *trace_ << "NodeIdOneOf error: wrong kind " << node_kind
  191. << ", expected ";
  192. trace_kinds();
  193. *trace_ << "\n";
  194. }
  195. }
  196. return false;
  197. }
  198. if (trace_) {
  199. *trace_ << "NodeIdOneOf ";
  200. trace_kinds();
  201. *trace_ << ": " << node_kind << " consumed\n";
  202. }
  203. return true;
  204. }
  205. // Extract a `NodeIdOneOf<T...>` as a single required child.
  206. template <typename... T>
  207. struct Extractable<NodeIdOneOf<T...>> {
  208. static auto Extract(NodeExtractor& extractor)
  209. -> std::optional<NodeIdOneOf<T...>> {
  210. if (extractor.MatchesNodeIdOneOf({T::Kind...})) {
  211. return NodeIdOneOf<T...>(extractor.ExtractNode());
  212. } else {
  213. return std::nullopt;
  214. }
  215. }
  216. };
  217. // Extract a `NodeIdNot<T>` as a single required child.
  218. // Note: this is only instantiated once, so no need to create a helper function.
  219. template <typename T>
  220. struct Extractable<NodeIdNot<T>> {
  221. static auto Extract(NodeExtractor& extractor) -> std::optional<NodeIdNot<T>> {
  222. if (extractor.at_end() || extractor.kind() == T::Kind) {
  223. if (auto* trace = extractor.trace()) {
  224. if (extractor.at_end()) {
  225. *trace << "NodeIdNot " << T::Kind << " error: no more children\n";
  226. } else {
  227. *trace << "NodeIdNot error: unexpected " << T::Kind << "\n";
  228. }
  229. }
  230. return std::nullopt;
  231. }
  232. if (auto* trace = extractor.trace()) {
  233. *trace << "NodeIdNot " << T::Kind << ": " << extractor.kind()
  234. << " consumed\n";
  235. }
  236. return NodeIdNot<T>(extractor.ExtractNode());
  237. }
  238. };
  239. // Extract an `llvm::SmallVector<T>` by extracting `T`s until we can't.
  240. template <typename T>
  241. struct Extractable<llvm::SmallVector<T>> {
  242. static auto Extract(NodeExtractor& extractor)
  243. -> std::optional<llvm::SmallVector<T>> {
  244. if (auto* trace = extractor.trace()) {
  245. *trace << "Vector: begin\n";
  246. }
  247. llvm::SmallVector<T> result;
  248. while (!extractor.at_end()) {
  249. auto checkpoint = extractor.Checkpoint();
  250. auto item = Extractable<T>::Extract(extractor);
  251. if (!item.has_value()) {
  252. extractor.RestoreCheckpoint(checkpoint);
  253. break;
  254. }
  255. result.push_back(*item);
  256. }
  257. std::reverse(result.begin(), result.end());
  258. if (auto* trace = extractor.trace()) {
  259. *trace << "Vector: end\n";
  260. }
  261. return result;
  262. }
  263. };
  264. // Extract an `optional<T>` from a list of child nodes by attempting to extract
  265. // a `T`, and extracting nothing if that fails.
  266. template <typename T>
  267. struct Extractable<std::optional<T>> {
  268. static auto Extract(NodeExtractor& extractor)
  269. -> std::optional<std::optional<T>> {
  270. if (auto* trace = extractor.trace()) {
  271. *trace << "Optional " << typeid(T).name() << ": begin\n";
  272. }
  273. auto checkpoint = extractor.Checkpoint();
  274. std::optional<T> value = Extractable<T>::Extract(extractor);
  275. if (value) {
  276. if (auto* trace = extractor.trace()) {
  277. *trace << "Optional " << typeid(T).name() << ": found\n";
  278. }
  279. return value;
  280. }
  281. if (auto* trace = extractor.trace()) {
  282. *trace << "Optional " << typeid(T).name() << ": missing\n";
  283. }
  284. extractor.RestoreCheckpoint(checkpoint);
  285. return value;
  286. }
  287. };
  288. auto NodeExtractor::MatchesTokenKind(Lex::TokenKind expected_kind) const
  289. -> bool {
  290. if (!node_id_.is_valid()) {
  291. if (trace_) {
  292. *trace_ << "Token " << expected_kind
  293. << " expected but processing root node\n";
  294. }
  295. return false;
  296. }
  297. if (token_kind() != expected_kind) {
  298. if (trace_) {
  299. *trace_ << "Token " << expected_kind << " expected for "
  300. << tree_->tree().node_kind(node_id_) << ", found " << token_kind()
  301. << "\n";
  302. }
  303. return false;
  304. }
  305. return true;
  306. }
  307. // Extract the token corresponding to a node.
  308. template <const Lex::TokenKind& Kind>
  309. struct Extractable<Lex::TokenIndexForKind<Kind>> {
  310. static auto Extract(NodeExtractor& extractor)
  311. -> std::optional<Lex::TokenIndexForKind<Kind>> {
  312. if (extractor.MatchesTokenKind(Kind)) {
  313. return static_cast<Lex::TokenIndexForKind<Kind>>(extractor.token());
  314. } else {
  315. return std::nullopt;
  316. }
  317. }
  318. };
  319. // Extract the token corresponding to a node.
  320. template <>
  321. struct Extractable<Lex::TokenIndex> {
  322. static auto Extract(NodeExtractor& extractor)
  323. -> std::optional<Lex::TokenIndex> {
  324. if (!extractor.has_token()) {
  325. if (auto* trace = extractor.trace()) {
  326. *trace << "Token expected but processing root node\n";
  327. }
  328. return std::nullopt;
  329. }
  330. return extractor.token();
  331. }
  332. };
  333. template <typename T, typename... U, std::size_t... Index>
  334. auto NodeExtractor::ExtractTupleLikeType(
  335. std::index_sequence<Index...> /*indices*/, std::tuple<U...>* /*type*/)
  336. -> std::optional<T> {
  337. std::tuple<std::optional<U>...> fields;
  338. if (trace_) {
  339. *trace_ << "Aggregate " << typeid(T).name() << ": begin\n";
  340. }
  341. // Use a fold over the `=` operator to parse fields from right to left.
  342. [[maybe_unused]] int unused;
  343. bool ok = true;
  344. static_cast<void>(
  345. ((ok && (ok = (std::get<Index>(fields) = Extractable<U>::Extract(*this))
  346. .has_value()),
  347. unused) = ... = 0));
  348. if (!ok) {
  349. if (trace_) {
  350. *trace_ << "Aggregate " << typeid(T).name() << ": error\n";
  351. }
  352. return std::nullopt;
  353. }
  354. if (trace_) {
  355. *trace_ << "Aggregate " << typeid(T).name() << ": success\n";
  356. }
  357. return T{std::move(std::get<Index>(fields).value())...};
  358. }
  359. namespace {
  360. // Extract the fields of a simple aggregate type.
  361. template <typename T>
  362. struct Extractable {
  363. static_assert(std::is_aggregate_v<T>, "Unsupported child type");
  364. static auto ExtractImpl(NodeExtractor& extractor) -> std::optional<T> {
  365. // Compute the corresponding tuple type.
  366. using TupleType = decltype(StructReflection::AsTuple(std::declval<T>()));
  367. return extractor.ExtractTupleLikeType<T>(
  368. std::make_index_sequence<std::tuple_size_v<TupleType>>(),
  369. static_cast<TupleType*>(nullptr));
  370. }
  371. static auto Extract(NodeExtractor& extractor) -> std::optional<T> {
  372. static_assert(!HasKindMember<T>, "Missing Id suffix");
  373. return ExtractImpl(extractor);
  374. }
  375. };
  376. } // namespace
  377. template <typename T>
  378. auto TreeAndSubtrees::TryExtractNodeFromChildren(
  379. NodeId node_id,
  380. llvm::iterator_range<TreeAndSubtrees::SiblingIterator> children,
  381. ErrorBuilder* trace) const -> std::optional<T> {
  382. NodeExtractor extractor(this, tokens_, trace, node_id, children);
  383. auto result = Extractable<T>::ExtractImpl(extractor);
  384. if (!extractor.at_end()) {
  385. if (trace) {
  386. *trace << "Error: " << tree_->node_kind(extractor.ExtractNode())
  387. << " node left unconsumed.";
  388. }
  389. return std::nullopt;
  390. }
  391. return result;
  392. }
  393. // Manually instantiate Tree::TryExtractNodeFromChildren
  394. #define CARBON_PARSE_NODE_KIND(KindName) \
  395. template auto TreeAndSubtrees::TryExtractNodeFromChildren<KindName>( \
  396. NodeId node_id, \
  397. llvm::iterator_range<TreeAndSubtrees::SiblingIterator> children, \
  398. ErrorBuilder * trace) const -> std::optional<KindName>;
  399. // Also instantiate for `File`, even though it isn't a parse node.
  400. CARBON_PARSE_NODE_KIND(File)
  401. #include "toolchain/parse/node_kind.def"
  402. auto TreeAndSubtrees::ExtractFile() const -> File {
  403. return ExtractNodeFromChildren<File>(NodeId::Invalid, roots());
  404. }
  405. } // namespace Carbon::Parse