extract.cpp 14 KB

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