extract.cpp 14 KB

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