extract.cpp 14 KB

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