node_stack.h 29 KB

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