node_stack.h 29 KB

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