extract.cpp 14 KB

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