extract.cpp 14 KB

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