node_stack.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. #ifndef CARBON_TOOLCHAIN_CHECK_NODE_STACK_H_
  5. #define CARBON_TOOLCHAIN_CHECK_NODE_STACK_H_
  6. #include "common/vlog.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "toolchain/parse/node_ids.h"
  9. #include "toolchain/parse/node_kind.h"
  10. #include "toolchain/parse/tree.h"
  11. #include "toolchain/parse/typed_nodes.h"
  12. #include "toolchain/sem_ir/id_kind.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. namespace Carbon::Check {
  15. // A non-discriminated union of ID types.
  16. class IdUnion {
  17. public:
  18. // The default constructor forms an invalid ID.
  19. explicit constexpr IdUnion() : index(AnyIdBase::InvalidIndex) {}
  20. template <typename IdT>
  21. requires SemIR::IdKind::Contains<IdT>
  22. explicit constexpr IdUnion(IdT id) : index(id.index) {}
  23. using Kind = SemIR::IdKind::RawEnumType;
  24. // Returns the ID given its type.
  25. template <typename IdT>
  26. requires SemIR::IdKind::Contains<IdT>
  27. constexpr auto As() const -> IdT {
  28. return IdT(index);
  29. }
  30. // Returns the ID given its kind.
  31. template <SemIR::IdKind::RawEnumType K>
  32. constexpr auto As() const -> SemIR::IdKind::TypeFor<K> {
  33. return As<SemIR::IdKind::TypeFor<K>>();
  34. }
  35. // Translates an ID type to the enum ID kind. Returns Invalid if `IdT` isn't
  36. // a type that can be stored in this union.
  37. template <typename IdT>
  38. static constexpr auto KindFor() -> Kind {
  39. return SemIR::IdKind::For<IdT>;
  40. }
  41. private:
  42. decltype(AnyIdBase::index) index;
  43. };
  44. // The stack of parse nodes representing the current state of a Check::Context.
  45. // Each parse node can have an associated id of some kind (instruction,
  46. // instruction block, function, class, ...).
  47. //
  48. // All pushes and pops will be vlogged.
  49. //
  50. // Pop APIs will run basic verification:
  51. //
  52. // - If receiving a Parse::NodeKind, verify that the node_id being popped has
  53. // that kind. Similarly, if receiving a Parse::NodeCategory, make sure the
  54. // of the popped node_id overlaps that category.
  55. // - Validates the kind of id data in the node based on the kind or category of
  56. // the node_id.
  57. //
  58. // These should be assumed API constraints unless otherwise mentioned on a
  59. // method. The main exception is PopAndIgnore, which doesn't do verification.
  60. class NodeStack {
  61. public:
  62. explicit NodeStack(const Parse::Tree& parse_tree,
  63. llvm::raw_ostream* vlog_stream)
  64. : parse_tree_(&parse_tree), vlog_stream_(vlog_stream) {}
  65. // Pushes a solo parse tree node onto the stack. Used when there is no
  66. // IR generated by the node.
  67. auto Push(Parse::NodeId node_id) -> void {
  68. auto kind = parse_tree_->node_kind(node_id);
  69. CARBON_CHECK(NodeKindToIdKind(kind) == Id::Kind::None,
  70. "Parse kind expects an Id: {0}", kind);
  71. CARBON_VLOG("Node Push {0}: {1} -> <none>\n", stack_.size(), kind);
  72. CARBON_CHECK(stack_.size() < (1 << 20),
  73. "Excessive stack size: likely infinite loop");
  74. stack_.push_back({.node_id = node_id, .id = Id()});
  75. }
  76. // Pushes a parse tree node onto the stack with an ID.
  77. template <typename IdT>
  78. auto Push(Parse::NodeId node_id, IdT id) -> void {
  79. auto kind = parse_tree_->node_kind(node_id);
  80. CARBON_CHECK(NodeKindToIdKind(kind) == Id::KindFor<IdT>(),
  81. "Parse kind expected a different IdT: {0} -> {1}\n", kind, id);
  82. CARBON_CHECK(id.is_valid(), "Push called with invalid id: {0}",
  83. parse_tree_->node_kind(node_id));
  84. CARBON_VLOG("Node Push {0}: {1} -> {2}\n", stack_.size(), kind, id);
  85. CARBON_CHECK(stack_.size() < (1 << 20),
  86. "Excessive stack size: likely infinite loop");
  87. stack_.push_back({.node_id = node_id, .id = Id(id)});
  88. }
  89. // Returns whether there is a node of the specified kind on top of the stack.
  90. auto PeekIs(Parse::NodeKind kind) const -> bool {
  91. return !stack_.empty() && PeekNodeKind() == kind;
  92. }
  93. // Returns whether there is a node of the specified kind on top of the stack.
  94. // Templated for consistency with other functions taking a parse node kind.
  95. template <const Parse::NodeKind& RequiredParseKind>
  96. auto PeekIs() const -> bool {
  97. return PeekIs(RequiredParseKind);
  98. }
  99. // Returns whether the node on the top of the stack has an overlapping
  100. // category.
  101. auto PeekIs(Parse::NodeCategory category) const -> bool {
  102. return !stack_.empty() && PeekNodeKind().category().HasAnyOf(category);
  103. }
  104. // Returns whether the node on the top of the stack has an overlapping
  105. // category. Templated for consistency with other functions taking a parse
  106. // node category.
  107. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  108. auto PeekIs() const -> bool {
  109. return PeekIs(RequiredParseCategory);
  110. }
  111. // Returns whether there is a node with the corresponding ID on top of the
  112. // stack.
  113. template <typename IdT>
  114. auto PeekIs() const -> bool {
  115. return !stack_.empty() &&
  116. NodeKindToIdKind(PeekNodeKind()) == Id::KindFor<IdT>();
  117. }
  118. // Returns whether the *next* node on the stack is a given kind. This doesn't
  119. // have the breadth of support versus other Peek functions because it's
  120. // expected to be used in narrow circumstances when determining how to treat
  121. // the *current* top of the stack.
  122. template <const Parse::NodeKind& RequiredParseKind>
  123. auto PeekNextIs() const -> bool {
  124. CARBON_CHECK(stack_.size() >= 2);
  125. return parse_tree_->node_kind(stack_[stack_.size() - 2].node_id) ==
  126. RequiredParseKind;
  127. }
  128. // Pops the top of the stack without any verification.
  129. auto PopAndIgnore() -> void {
  130. Entry back = stack_.pop_back_val();
  131. CARBON_VLOG("Node Pop {0}: {1} -> <ignored>\n", stack_.size(),
  132. parse_tree_->node_kind(back.node_id));
  133. }
  134. // Pops the top of the stack and returns the node_id.
  135. template <const Parse::NodeKind& RequiredParseKind>
  136. auto PopForSoloNodeId() -> Parse::NodeIdForKind<RequiredParseKind> {
  137. Entry back = PopEntry<SemIR::InstId>();
  138. RequireIdKind(RequiredParseKind, Id::Kind::None);
  139. RequireParseKind<RequiredParseKind>(back.node_id);
  140. return Parse::NodeIdForKind<RequiredParseKind>(back.node_id);
  141. }
  142. // Pops the top of the stack if it is the given kind, and returns the
  143. // node_id. Otherwise, returns std::nullopt.
  144. template <const Parse::NodeKind& RequiredParseKind>
  145. auto PopForSoloNodeIdIf()
  146. -> std::optional<Parse::NodeIdForKind<RequiredParseKind>> {
  147. if (PeekIs<RequiredParseKind>()) {
  148. return PopForSoloNodeId<RequiredParseKind>();
  149. }
  150. return std::nullopt;
  151. }
  152. // Pops the top of the stack.
  153. template <const Parse::NodeKind& RequiredParseKind>
  154. auto PopAndDiscardSoloNodeId() -> void {
  155. PopForSoloNodeId<RequiredParseKind>();
  156. }
  157. // Pops the top of the stack if it is the given kind. Returns `true` if a node
  158. // was popped.
  159. template <const Parse::NodeKind& RequiredParseKind>
  160. auto PopAndDiscardSoloNodeIdIf() -> bool {
  161. if (!PeekIs<RequiredParseKind>()) {
  162. return false;
  163. }
  164. PopForSoloNodeId<RequiredParseKind>();
  165. return true;
  166. }
  167. // Pops an expression from the top of the stack and returns the node_id and
  168. // the ID.
  169. auto PopExprWithNodeId() -> std::pair<Parse::AnyExprId, SemIR::InstId>;
  170. // Pops a pattern from the top of the stack and returns the node_id and
  171. // the ID.
  172. auto PopPatternWithNodeId() -> std::pair<Parse::NodeId, SemIR::InstId> {
  173. return PopWithNodeId<SemIR::InstId>();
  174. }
  175. // Pops a name from the top of the stack and returns the node_id and
  176. // the ID.
  177. auto PopNameWithNodeId() -> std::pair<Parse::NodeId, SemIR::NameId> {
  178. return PopWithNodeId<SemIR::NameId>();
  179. }
  180. // Pops the top of the stack and returns the node_id and the ID.
  181. template <const Parse::NodeKind& RequiredParseKind>
  182. auto PopWithNodeId() -> auto {
  183. auto id = Peek<RequiredParseKind>();
  184. Parse::NodeIdForKind<RequiredParseKind> node_id(
  185. stack_.pop_back_val().node_id);
  186. return std::make_pair(node_id, id);
  187. }
  188. // Pops the top of the stack and returns the node_id and the ID.
  189. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  190. auto PopWithNodeId() -> auto {
  191. auto id = Peek<RequiredParseCategory>();
  192. Parse::NodeIdInCategory<RequiredParseCategory> node_id(
  193. stack_.pop_back_val().node_id);
  194. return std::make_pair(node_id, id);
  195. }
  196. // Pops an expression from the top of the stack and returns the ID.
  197. // Expressions always map Parse::NodeCategory::Expr nodes to SemIR::InstId.
  198. auto PopExpr() -> SemIR::InstId { return PopExprWithNodeId().second; }
  199. // Pops a pattern from the top of the stack and returns the ID.
  200. // Patterns map multiple Parse::NodeKinds to SemIR::InstId always.
  201. auto PopPattern() -> SemIR::InstId { return PopPatternWithNodeId().second; }
  202. // Pops a name from the top of the stack and returns the ID.
  203. auto PopName() -> SemIR::NameId { return PopNameWithNodeId().second; }
  204. // Pops the top of the stack and returns the ID.
  205. template <const Parse::NodeKind& RequiredParseKind>
  206. auto Pop() -> auto {
  207. return PopWithNodeId<RequiredParseKind>().second;
  208. }
  209. // Pops the top of the stack and returns the ID.
  210. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  211. auto Pop() -> auto {
  212. return PopWithNodeId<RequiredParseCategory>().second;
  213. }
  214. // Pops the top of the stack and returns the ID.
  215. template <typename IdT>
  216. auto Pop() -> IdT {
  217. return PopWithNodeId<IdT>().second;
  218. }
  219. // Pops the top of the stack if it has the given kind, and returns the ID.
  220. // Otherwise returns std::nullopt.
  221. template <const Parse::NodeKind& RequiredParseKind>
  222. auto PopIf() -> std::optional<decltype(Pop<RequiredParseKind>())> {
  223. if (PeekIs<RequiredParseKind>()) {
  224. return Pop<RequiredParseKind>();
  225. }
  226. return std::nullopt;
  227. }
  228. // Pops the top of the stack if it has the given category, and returns the ID.
  229. // Otherwise returns std::nullopt.
  230. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  231. auto PopIf() -> std::optional<decltype(Pop<RequiredParseCategory>())> {
  232. if (PeekIs<RequiredParseCategory>()) {
  233. return Pop<RequiredParseCategory>();
  234. }
  235. return std::nullopt;
  236. }
  237. // Pops the top of the stack if it has the given category, and returns the ID.
  238. // Otherwise returns std::nullopt.
  239. template <typename IdT>
  240. auto PopIf() -> std::optional<IdT> {
  241. if (PeekIs<IdT>()) {
  242. return Pop<IdT>();
  243. }
  244. return std::nullopt;
  245. }
  246. // Pops the top of the stack and returns the node_id and the ID if it is
  247. // of the specified kind.
  248. template <const Parse::NodeKind& RequiredParseKind>
  249. auto PopWithNodeIdIf() -> std::pair<Parse::NodeIdForKind<RequiredParseKind>,
  250. decltype(PopIf<RequiredParseKind>())> {
  251. if (!PeekIs<RequiredParseKind>()) {
  252. return {Parse::NodeId::Invalid, std::nullopt};
  253. }
  254. return PopWithNodeId<RequiredParseKind>();
  255. }
  256. // Pops the top of the stack and returns the node_id and the ID if it is
  257. // of the specified category.
  258. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  259. auto PopWithNodeIdIf()
  260. -> std::pair<Parse::NodeIdInCategory<RequiredParseCategory>,
  261. decltype(PopIf<RequiredParseCategory>())> {
  262. if (!PeekIs<RequiredParseCategory>()) {
  263. return {Parse::NodeId::Invalid, std::nullopt};
  264. }
  265. return PopWithNodeId<RequiredParseCategory>();
  266. }
  267. // Peeks at the parse node of the top of the node stack.
  268. auto PeekNodeId() const -> Parse::NodeId { return stack_.back().node_id; }
  269. // Peeks at the kind of the parse node of the top of the node stack.
  270. auto PeekNodeKind() const -> Parse::NodeKind {
  271. return parse_tree_->node_kind(PeekNodeId());
  272. }
  273. // Peeks at the ID associated with the top of the name stack.
  274. template <const Parse::NodeKind& RequiredParseKind>
  275. auto Peek() const -> auto {
  276. Entry back = stack_.back();
  277. RequireParseKind<RequiredParseKind>(back.node_id);
  278. constexpr Id::Kind RequiredIdKind = NodeKindToIdKind(RequiredParseKind);
  279. return Peek<RequiredIdKind>();
  280. }
  281. // Peeks at the ID associated with the top of the name stack.
  282. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  283. auto Peek() const -> auto {
  284. Entry back = stack_.back();
  285. RequireParseCategory<RequiredParseCategory>(back.node_id);
  286. constexpr std::optional<Id::Kind> RequiredIdKind =
  287. NodeCategoryToIdKind(RequiredParseCategory, false);
  288. static_assert(RequiredIdKind.has_value());
  289. return Peek<*RequiredIdKind>();
  290. }
  291. // Prints the stack for a stack dump.
  292. auto PrintForStackDump(int indent, llvm::raw_ostream& output) const -> void;
  293. auto empty() const -> bool { return stack_.empty(); }
  294. auto size() const -> size_t { return stack_.size(); }
  295. protected:
  296. // An ID that can be associated with a parse node.
  297. //
  298. // Each parse node kind has a corresponding Id::Kind indicating which kind of
  299. // ID is stored, computed by NodeKindToIdKind. Id::Kind::None indicates
  300. // that the parse node has no associated ID, in which case the *SoloNodeId
  301. // functions should be used to push and pop it. Id::Kind::Invalid indicates
  302. // that the parse node should not appear in the node stack at all.
  303. using Id = IdUnion;
  304. // An entry in stack_.
  305. struct Entry {
  306. // The parse node associated with the stack entry.
  307. Parse::NodeId node_id;
  308. // The ID associated with this parse node. The kind of ID is determined by
  309. // the kind of the parse node, so a separate discriminiator is not needed.
  310. Id id;
  311. };
  312. static_assert(sizeof(Entry) == 8, "Unexpected Entry size");
  313. // Translate a parse node category to the enum ID kind it should always
  314. // provide, if it is consistent.
  315. static constexpr auto NodeCategoryToIdKind(Parse::NodeCategory category,
  316. bool for_node_kind)
  317. -> std::optional<Id::Kind> {
  318. std::optional<Id::Kind> result;
  319. auto set_id_if_category_is = [&](Parse::NodeCategory cat, Id::Kind kind) {
  320. if (category.HasAnyOf(cat)) {
  321. // Check for no consistent Id::Kind due to category with multiple bits
  322. // set. When computing the Id::Kind for a node kind, a partial category
  323. // match is OK, so long as we don't match two inconsistent categories.
  324. // When computing the Id::Kind for a category query, the query can't
  325. // have any extra bits set or we could be popping a node that is not in
  326. // this category.
  327. if (for_node_kind ? result.has_value() : category.HasAnyOf(~cat)) {
  328. result = Id::Kind::Invalid;
  329. } else {
  330. result = kind;
  331. }
  332. }
  333. };
  334. // TODO: Patterns should also produce an `InstId`, but currently
  335. // `TuplePattern` produces an `InstBlockId`.
  336. set_id_if_category_is(Parse::NodeCategory::Expr,
  337. Id::KindFor<SemIR::InstId>());
  338. set_id_if_category_is(Parse::NodeCategory::MemberName,
  339. Id::KindFor<SemIR::NameId>());
  340. set_id_if_category_is(Parse::NodeCategory::ImplAs,
  341. Id::KindFor<SemIR::InstId>());
  342. set_id_if_category_is(Parse::NodeCategory::Decl |
  343. Parse::NodeCategory::Statement |
  344. Parse::NodeCategory::Modifier,
  345. Id::Kind::None);
  346. return result;
  347. }
  348. using IdKindTableType = std::array<Id::Kind, Parse::NodeKind::ValidCount>;
  349. // Lookup table to implement `NodeKindToIdKind`. Initialized to the
  350. // return value of `ComputeIdKindTable()`.
  351. static const IdKindTableType IdKindTable;
  352. static constexpr auto ComputeIdKindTable() -> IdKindTableType {
  353. IdKindTableType table = {};
  354. auto to_id_kind =
  355. [](const Parse::NodeKind::Definition& node_kind) -> Id::Kind {
  356. if (auto from_category =
  357. NodeCategoryToIdKind(node_kind.category(), true)) {
  358. return *from_category;
  359. }
  360. switch (node_kind) {
  361. case Parse::NodeKind::Addr:
  362. case Parse::NodeKind::BindingPattern:
  363. case Parse::NodeKind::CallExprStart:
  364. case Parse::NodeKind::CompileTimeBindingPattern:
  365. case Parse::NodeKind::IfExprThen:
  366. case Parse::NodeKind::ReturnType:
  367. case Parse::NodeKind::ShortCircuitOperandAnd:
  368. case Parse::NodeKind::ShortCircuitOperandOr:
  369. case Parse::NodeKind::StructLiteralField:
  370. case Parse::NodeKind::WhereOperand:
  371. return Id::KindFor<SemIR::InstId>();
  372. case Parse::NodeKind::IfCondition:
  373. case Parse::NodeKind::IfExprIf:
  374. case Parse::NodeKind::ImplForall:
  375. case Parse::NodeKind::ImplicitParamList:
  376. case Parse::NodeKind::TuplePattern:
  377. case Parse::NodeKind::WhileCondition:
  378. case Parse::NodeKind::WhileConditionStart:
  379. return Id::KindFor<SemIR::InstBlockId>();
  380. case Parse::NodeKind::FunctionDefinitionStart:
  381. case Parse::NodeKind::BuiltinFunctionDefinitionStart:
  382. return Id::KindFor<SemIR::FunctionId>();
  383. case Parse::NodeKind::ClassDefinitionStart:
  384. return Id::KindFor<SemIR::ClassId>();
  385. case Parse::NodeKind::InterfaceDefinitionStart:
  386. return Id::KindFor<SemIR::InterfaceId>();
  387. case Parse::NodeKind::ImplDefinitionStart:
  388. return Id::KindFor<SemIR::ImplId>();
  389. case Parse::NodeKind::SelfTypeName:
  390. case Parse::NodeKind::SelfValueName:
  391. return Id::KindFor<SemIR::NameId>();
  392. case Parse::NodeKind::DefaultLibrary:
  393. case Parse::NodeKind::LibraryName:
  394. return Id::KindFor<SemIR::LibraryNameId>();
  395. case Parse::NodeKind::ArrayExprSemi:
  396. case Parse::NodeKind::BuiltinName:
  397. case Parse::NodeKind::ClassIntroducer:
  398. case Parse::NodeKind::CodeBlockStart:
  399. case Parse::NodeKind::FunctionIntroducer:
  400. case Parse::NodeKind::IfStatementElse:
  401. case Parse::NodeKind::ImplicitParamListStart:
  402. case Parse::NodeKind::ImplIntroducer:
  403. case Parse::NodeKind::InterfaceIntroducer:
  404. case Parse::NodeKind::LetInitializer:
  405. case Parse::NodeKind::LetIntroducer:
  406. case Parse::NodeKind::ReturnedModifier:
  407. case Parse::NodeKind::ReturnStatementStart:
  408. case Parse::NodeKind::ReturnVarModifier:
  409. case Parse::NodeKind::StructLiteralStart:
  410. case Parse::NodeKind::StructTypeLiteralField:
  411. case Parse::NodeKind::StructTypeLiteralStart:
  412. case Parse::NodeKind::TupleLiteralStart:
  413. case Parse::NodeKind::TuplePatternStart:
  414. case Parse::NodeKind::VariableInitializer:
  415. case Parse::NodeKind::VariableIntroducer:
  416. return Id::Kind::None;
  417. case Parse::NodeKind::AbstractModifier:
  418. case Parse::NodeKind::AdaptDecl:
  419. case Parse::NodeKind::AdaptIntroducer:
  420. case Parse::NodeKind::Alias:
  421. case Parse::NodeKind::AliasInitializer:
  422. case Parse::NodeKind::AliasIntroducer:
  423. case Parse::NodeKind::ArrayExpr:
  424. case Parse::NodeKind::ArrayExprStart:
  425. case Parse::NodeKind::AutoTypeLiteral:
  426. case Parse::NodeKind::BaseColon:
  427. case Parse::NodeKind::BaseDecl:
  428. case Parse::NodeKind::BaseIntroducer:
  429. case Parse::NodeKind::BaseModifier:
  430. case Parse::NodeKind::BaseName:
  431. case Parse::NodeKind::BoolLiteralFalse:
  432. case Parse::NodeKind::BoolLiteralTrue:
  433. case Parse::NodeKind::BoolTypeLiteral:
  434. case Parse::NodeKind::BreakStatement:
  435. case Parse::NodeKind::BreakStatementStart:
  436. case Parse::NodeKind::BuiltinFunctionDefinition:
  437. case Parse::NodeKind::CallExpr:
  438. case Parse::NodeKind::CallExprComma:
  439. case Parse::NodeKind::ChoiceAlternativeListComma:
  440. case Parse::NodeKind::ChoiceDefinition:
  441. case Parse::NodeKind::ChoiceDefinitionStart:
  442. case Parse::NodeKind::ChoiceIntroducer:
  443. case Parse::NodeKind::ClassDecl:
  444. case Parse::NodeKind::ClassDefinition:
  445. case Parse::NodeKind::CodeBlock:
  446. case Parse::NodeKind::ContinueStatement:
  447. case Parse::NodeKind::ContinueStatementStart:
  448. case Parse::NodeKind::DefaultModifier:
  449. case Parse::NodeKind::DefaultSelfImplAs:
  450. case Parse::NodeKind::DesignatorExpr:
  451. case Parse::NodeKind::EmptyDecl:
  452. case Parse::NodeKind::ExportDecl:
  453. case Parse::NodeKind::ExportIntroducer:
  454. case Parse::NodeKind::ExportModifier:
  455. case Parse::NodeKind::ExprStatement:
  456. case Parse::NodeKind::ExtendModifier:
  457. case Parse::NodeKind::ExternModifier:
  458. case Parse::NodeKind::ExternModifierWithLibrary:
  459. case Parse::NodeKind::FileEnd:
  460. case Parse::NodeKind::FileStart:
  461. case Parse::NodeKind::FinalModifier:
  462. case Parse::NodeKind::FloatTypeLiteral:
  463. case Parse::NodeKind::ForHeader:
  464. case Parse::NodeKind::ForHeaderStart:
  465. case Parse::NodeKind::ForIn:
  466. case Parse::NodeKind::ForStatement:
  467. case Parse::NodeKind::FunctionDecl:
  468. case Parse::NodeKind::FunctionDefinition:
  469. case Parse::NodeKind::IdentifierName:
  470. case Parse::NodeKind::IdentifierNameExpr:
  471. case Parse::NodeKind::IfConditionStart:
  472. case Parse::NodeKind::IfExprElse:
  473. case Parse::NodeKind::IfStatement:
  474. case Parse::NodeKind::ImplDecl:
  475. case Parse::NodeKind::ImplDefinition:
  476. case Parse::NodeKind::ImplModifier:
  477. case Parse::NodeKind::ImportDecl:
  478. case Parse::NodeKind::ImportIntroducer:
  479. case Parse::NodeKind::IndexExpr:
  480. case Parse::NodeKind::IndexExprStart:
  481. case Parse::NodeKind::InfixOperatorAmp:
  482. case Parse::NodeKind::InfixOperatorAmpEqual:
  483. case Parse::NodeKind::InfixOperatorAs:
  484. case Parse::NodeKind::InfixOperatorCaret:
  485. case Parse::NodeKind::InfixOperatorCaretEqual:
  486. case Parse::NodeKind::InfixOperatorEqual:
  487. case Parse::NodeKind::InfixOperatorEqualEqual:
  488. case Parse::NodeKind::InfixOperatorExclaimEqual:
  489. case Parse::NodeKind::InfixOperatorGreater:
  490. case Parse::NodeKind::InfixOperatorGreaterEqual:
  491. case Parse::NodeKind::InfixOperatorGreaterGreater:
  492. case Parse::NodeKind::InfixOperatorGreaterGreaterEqual:
  493. case Parse::NodeKind::InfixOperatorLess:
  494. case Parse::NodeKind::InfixOperatorLessEqual:
  495. case Parse::NodeKind::InfixOperatorLessEqualGreater:
  496. case Parse::NodeKind::InfixOperatorLessLess:
  497. case Parse::NodeKind::InfixOperatorLessLessEqual:
  498. case Parse::NodeKind::InfixOperatorMinus:
  499. case Parse::NodeKind::InfixOperatorMinusEqual:
  500. case Parse::NodeKind::InfixOperatorPercent:
  501. case Parse::NodeKind::InfixOperatorPercentEqual:
  502. case Parse::NodeKind::InfixOperatorPipe:
  503. case Parse::NodeKind::InfixOperatorPipeEqual:
  504. case Parse::NodeKind::InfixOperatorPlus:
  505. case Parse::NodeKind::InfixOperatorPlusEqual:
  506. case Parse::NodeKind::InfixOperatorSlash:
  507. case Parse::NodeKind::InfixOperatorSlashEqual:
  508. case Parse::NodeKind::InfixOperatorStar:
  509. case Parse::NodeKind::InfixOperatorStarEqual:
  510. case Parse::NodeKind::InterfaceDecl:
  511. case Parse::NodeKind::InterfaceDefinition:
  512. case Parse::NodeKind::IntLiteral:
  513. case Parse::NodeKind::IntTypeLiteral:
  514. case Parse::NodeKind::InvalidParse:
  515. case Parse::NodeKind::InvalidParseStart:
  516. case Parse::NodeKind::InvalidParseSubtree:
  517. case Parse::NodeKind::LetDecl:
  518. case Parse::NodeKind::LibraryDecl:
  519. case Parse::NodeKind::LibraryIntroducer:
  520. case Parse::NodeKind::LibrarySpecifier:
  521. case Parse::NodeKind::MatchCase:
  522. case Parse::NodeKind::MatchCaseEqualGreater:
  523. case Parse::NodeKind::MatchCaseGuard:
  524. case Parse::NodeKind::MatchCaseGuardIntroducer:
  525. case Parse::NodeKind::MatchCaseGuardStart:
  526. case Parse::NodeKind::MatchCaseIntroducer:
  527. case Parse::NodeKind::MatchCaseStart:
  528. case Parse::NodeKind::MatchCondition:
  529. case Parse::NodeKind::MatchConditionStart:
  530. case Parse::NodeKind::MatchDefault:
  531. case Parse::NodeKind::MatchDefaultEqualGreater:
  532. case Parse::NodeKind::MatchDefaultIntroducer:
  533. case Parse::NodeKind::MatchDefaultStart:
  534. case Parse::NodeKind::MatchIntroducer:
  535. case Parse::NodeKind::MatchStatement:
  536. case Parse::NodeKind::MatchStatementStart:
  537. case Parse::NodeKind::MemberAccessExpr:
  538. case Parse::NodeKind::NamedConstraintDecl:
  539. case Parse::NodeKind::NamedConstraintDefinition:
  540. case Parse::NodeKind::NamedConstraintDefinitionStart:
  541. case Parse::NodeKind::NamedConstraintIntroducer:
  542. case Parse::NodeKind::NameQualifier:
  543. case Parse::NodeKind::Namespace:
  544. case Parse::NodeKind::NamespaceStart:
  545. case Parse::NodeKind::PackageDecl:
  546. case Parse::NodeKind::PackageExpr:
  547. case Parse::NodeKind::PackageIntroducer:
  548. case Parse::NodeKind::PackageName:
  549. case Parse::NodeKind::ParenExpr:
  550. case Parse::NodeKind::ParenExprStart:
  551. case Parse::NodeKind::PatternListComma:
  552. case Parse::NodeKind::Placeholder:
  553. case Parse::NodeKind::PointerMemberAccessExpr:
  554. case Parse::NodeKind::PostfixOperatorStar:
  555. case Parse::NodeKind::PrefixOperatorAmp:
  556. case Parse::NodeKind::PrefixOperatorCaret:
  557. case Parse::NodeKind::PrefixOperatorConst:
  558. case Parse::NodeKind::PrefixOperatorMinus:
  559. case Parse::NodeKind::PrefixOperatorMinusMinus:
  560. case Parse::NodeKind::PrefixOperatorNot:
  561. case Parse::NodeKind::PrefixOperatorPlusPlus:
  562. case Parse::NodeKind::PrefixOperatorStar:
  563. case Parse::NodeKind::PrivateModifier:
  564. case Parse::NodeKind::ProtectedModifier:
  565. case Parse::NodeKind::RealLiteral:
  566. case Parse::NodeKind::RequirementAnd:
  567. case Parse::NodeKind::RequirementEqual:
  568. case Parse::NodeKind::RequirementEqualEqual:
  569. case Parse::NodeKind::RequirementImpls:
  570. case Parse::NodeKind::ReturnStatement:
  571. case Parse::NodeKind::SelfTypeNameExpr:
  572. case Parse::NodeKind::SelfValueNameExpr:
  573. case Parse::NodeKind::ShortCircuitOperatorAnd:
  574. case Parse::NodeKind::ShortCircuitOperatorOr:
  575. case Parse::NodeKind::StringLiteral:
  576. case Parse::NodeKind::StringTypeLiteral:
  577. case Parse::NodeKind::StructLiteralComma:
  578. case Parse::NodeKind::StructFieldDesignator:
  579. case Parse::NodeKind::StructTypeLiteralComma:
  580. case Parse::NodeKind::StructLiteral:
  581. case Parse::NodeKind::StructTypeLiteral:
  582. case Parse::NodeKind::Template:
  583. case Parse::NodeKind::TupleLiteral:
  584. case Parse::NodeKind::TupleLiteralComma:
  585. case Parse::NodeKind::TypeImplAs:
  586. case Parse::NodeKind::TypeTypeLiteral:
  587. case Parse::NodeKind::UnsignedIntTypeLiteral:
  588. case Parse::NodeKind::VariableDecl:
  589. case Parse::NodeKind::VirtualModifier:
  590. case Parse::NodeKind::WhereExpr:
  591. case Parse::NodeKind::WhileStatement:
  592. return Id::Kind::Invalid;
  593. }
  594. };
  595. #define CARBON_PARSE_NODE_KIND(Name) \
  596. table[Parse::Name::Kind.AsInt()] = to_id_kind(Parse::Name::Kind);
  597. #include "toolchain/parse/node_kind.def"
  598. return table;
  599. }
  600. // Translate a parse node kind to the enum ID kind it should always provide.
  601. static constexpr auto NodeKindToIdKind(Parse::NodeKind kind) -> Id::Kind {
  602. return IdKindTable[kind.AsInt()];
  603. }
  604. // Peeks at the ID associated with the top of the name stack.
  605. template <Id::Kind RequiredIdKind>
  606. auto Peek() const -> auto {
  607. Id id = stack_.back().id;
  608. return id.As<RequiredIdKind>();
  609. }
  610. // Pops an entry.
  611. template <typename IdT>
  612. auto PopEntry() -> Entry {
  613. Entry back = stack_.pop_back_val();
  614. CARBON_VLOG("Node Pop {0}: {1} -> {2}\n", stack_.size(),
  615. parse_tree_->node_kind(back.node_id),
  616. back.id.template As<IdT>());
  617. return back;
  618. }
  619. // Pops the top of the stack and returns the node_id and the ID.
  620. template <typename IdT>
  621. auto PopWithNodeId() -> std::pair<Parse::NodeId, IdT> {
  622. Entry back = PopEntry<IdT>();
  623. RequireIdKind(parse_tree_->node_kind(back.node_id), Id::KindFor<IdT>());
  624. return {back.node_id, back.id.template As<IdT>()};
  625. }
  626. // Require a Parse::NodeKind be mapped to a particular Id::Kind.
  627. auto RequireIdKind(Parse::NodeKind parse_kind, Id::Kind id_kind) const
  628. -> void {
  629. CARBON_CHECK(NodeKindToIdKind(parse_kind) == id_kind,
  630. "Unexpected Id::Kind mapping for {0}: expected {1}, found {2}",
  631. parse_kind, SemIR::IdKind(id_kind),
  632. SemIR::IdKind(NodeKindToIdKind(parse_kind)));
  633. }
  634. // Require an entry to have the given Parse::NodeKind.
  635. template <const Parse::NodeKind& RequiredParseKind>
  636. auto RequireParseKind(Parse::NodeId node_id) const -> void {
  637. auto actual_kind = parse_tree_->node_kind(node_id);
  638. CARBON_CHECK(RequiredParseKind == actual_kind, "Expected {0}, found {1}",
  639. RequiredParseKind, actual_kind);
  640. }
  641. // Require an entry to have the given Parse::NodeCategory.
  642. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  643. auto RequireParseCategory(Parse::NodeId node_id) const -> void {
  644. auto kind = parse_tree_->node_kind(node_id);
  645. CARBON_CHECK(kind.category().HasAnyOf(RequiredParseCategory),
  646. "Expected {0}, found {1} with category {2}",
  647. RequiredParseCategory, kind, kind.category());
  648. }
  649. // The file's parse tree.
  650. const Parse::Tree* parse_tree_;
  651. // Whether to print verbose output.
  652. llvm::raw_ostream* vlog_stream_;
  653. // The actual stack.
  654. // PushEntry and PopEntry control modification in order to centralize
  655. // vlogging.
  656. llvm::SmallVector<Entry> stack_;
  657. };
  658. constexpr NodeStack::IdKindTableType NodeStack::IdKindTable =
  659. ComputeIdKindTable();
  660. inline auto NodeStack::PopExprWithNodeId()
  661. -> std::pair<Parse::AnyExprId, SemIR::InstId> {
  662. return PopWithNodeId<Parse::NodeCategory::Expr>();
  663. }
  664. } // namespace Carbon::Check
  665. #endif // CARBON_TOOLCHAIN_CHECK_NODE_STACK_H_