extract.cpp 14 KB

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