node_stack.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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 a `None` ID.
  19. explicit constexpr IdUnion() : index(AnyIdBase::NoneIndex) {}
  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 `None` 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.has_value(), "Push called with `None` 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. // TODO: TuplePatterns store an InstBlockId instead and must be dealt with as
  187. // a special case before calling this function.
  188. auto PopPattern() -> SemIR::InstId { return PopPatternWithNodeId().second; }
  189. // Pops a name from the top of the stack and returns the ID.
  190. auto PopName() -> SemIR::NameId { return PopNameWithNodeId().second; }
  191. // Pops the top of the stack and returns the ID.
  192. template <const Parse::NodeKind& RequiredParseKind>
  193. auto Pop() -> auto {
  194. return PopWithNodeId<RequiredParseKind>().second;
  195. }
  196. // Pops the top of the stack and returns the ID.
  197. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  198. auto Pop() -> auto {
  199. return PopWithNodeId<RequiredParseCategory>().second;
  200. }
  201. // Pops the top of the stack and returns the ID.
  202. template <typename IdT>
  203. auto Pop() -> IdT {
  204. return PopWithNodeId<IdT>().second;
  205. }
  206. // Pops the top of the stack if it has the given kind, and returns the ID.
  207. // Otherwise returns std::nullopt.
  208. template <const Parse::NodeKind& RequiredParseKind>
  209. auto PopIf() -> std::optional<decltype(Pop<RequiredParseKind>())> {
  210. if (PeekIs(RequiredParseKind)) {
  211. return Pop<RequiredParseKind>();
  212. }
  213. return std::nullopt;
  214. }
  215. // Pops the top of the stack if it has the given category, and returns the ID.
  216. // Otherwise returns std::nullopt.
  217. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  218. auto PopIf() -> std::optional<decltype(Pop<RequiredParseCategory>())> {
  219. if (PeekIs(RequiredParseCategory)) {
  220. return Pop<RequiredParseCategory>();
  221. }
  222. return std::nullopt;
  223. }
  224. // Pops the top of the stack if it has the given category, and returns the ID.
  225. // Otherwise returns std::nullopt.
  226. template <typename IdT>
  227. auto PopIf() -> std::optional<IdT> {
  228. if (PeekIs<IdT>()) {
  229. return Pop<IdT>();
  230. }
  231. return std::nullopt;
  232. }
  233. // Pops the top of the stack and returns the node_id and the ID if it is
  234. // of the specified kind.
  235. template <const Parse::NodeKind& RequiredParseKind>
  236. auto PopWithNodeIdIf() -> std::pair<Parse::NodeIdForKind<RequiredParseKind>,
  237. decltype(PopIf<RequiredParseKind>())> {
  238. if (!PeekIs(RequiredParseKind)) {
  239. return {Parse::NodeId::None, std::nullopt};
  240. }
  241. return PopWithNodeId<RequiredParseKind>();
  242. }
  243. // Pops the top of the stack and returns the node_id and the ID if it is
  244. // of the specified category.
  245. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  246. auto PopWithNodeIdIf()
  247. -> std::pair<Parse::NodeIdInCategory<RequiredParseCategory>,
  248. decltype(PopIf<RequiredParseCategory>())> {
  249. if (!PeekIs(RequiredParseCategory)) {
  250. return {Parse::NodeId::None, std::nullopt};
  251. }
  252. return PopWithNodeId<RequiredParseCategory>();
  253. }
  254. // Peeks at the parse node of the top of the node stack.
  255. auto PeekNodeId() const -> Parse::NodeId { return stack_.back().node_id; }
  256. // Peeks at the kind of the parse node of the top of the node stack.
  257. auto PeekNodeKind() const -> Parse::NodeKind {
  258. return parse_tree_->node_kind(PeekNodeId());
  259. }
  260. // Peeks at the ID associated with the top of the name stack.
  261. template <const Parse::NodeKind& RequiredParseKind>
  262. auto Peek() const -> auto {
  263. Entry back = stack_.back();
  264. RequireParseKind<RequiredParseKind>(back.node_id);
  265. constexpr Id::Kind RequiredIdKind = NodeKindToIdKind(RequiredParseKind);
  266. return Peek<RequiredIdKind>();
  267. }
  268. // Peeks at the ID associated with the top of the name stack.
  269. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  270. auto Peek() const -> auto {
  271. Entry back = stack_.back();
  272. RequireParseCategory<RequiredParseCategory>(back.node_id);
  273. constexpr std::optional<Id::Kind> RequiredIdKind =
  274. NodeCategoryToIdKind(RequiredParseCategory, false);
  275. static_assert(RequiredIdKind.has_value());
  276. return Peek<*RequiredIdKind>();
  277. }
  278. // Peeks at the ID associated with the pattern at the top of the stack.
  279. // Patterns map multiple Parse::NodeKinds to SemIR::InstId always.
  280. // TODO: TuplePatterns store an InstBlockId instead and must be dealt with as
  281. // a special case before calling this function.
  282. auto PeekPattern() const -> SemIR::InstId;
  283. // Prints the stack for a stack dump.
  284. auto PrintForStackDump(int indent, llvm::raw_ostream& output) const -> void;
  285. auto empty() const -> bool { return stack_.empty(); }
  286. auto size() const -> size_t { return stack_.size(); }
  287. private:
  288. // An ID that can be associated with a parse node.
  289. //
  290. // Each parse node kind has a corresponding Id::Kind indicating which kind of
  291. // ID is stored, computed by NodeKindToIdKind. Id::Kind::None indicates
  292. // that the parse node has no associated ID, in which case the *SoloNodeId
  293. // functions should be used to push and pop it. Id::Kind::Invalid indicates
  294. // that the parse node should not appear in the node stack at all.
  295. using Id = IdUnion;
  296. // An entry in stack_.
  297. struct Entry {
  298. // The parse node associated with the stack entry.
  299. Parse::NodeId node_id;
  300. // The ID associated with this parse node. The kind of ID is determined by
  301. // the kind of the parse node, so a separate discriminiator is not needed.
  302. Id id;
  303. };
  304. static_assert(sizeof(Entry) == 8, "Unexpected Entry size");
  305. // Translate a parse node category to the enum ID kind it should always
  306. // provide, if it is consistent.
  307. static constexpr auto NodeCategoryToIdKind(Parse::NodeCategory category,
  308. bool for_node_kind)
  309. -> std::optional<Id::Kind> {
  310. std::optional<Id::Kind> result;
  311. auto set_id_if_category_is = [&](Parse::NodeCategory cat, Id::Kind kind) {
  312. if (category.HasAnyOf(cat)) {
  313. // Check for no consistent Id::Kind due to category with multiple bits
  314. // set. When computing the Id::Kind for a node kind, a partial category
  315. // match is OK, so long as we don't match two inconsistent categories.
  316. // When computing the Id::Kind for a category query, the query can't
  317. // have any extra bits set or we could be popping a node that is not in
  318. // this category.
  319. if (for_node_kind ? result.has_value() : category.HasAnyOf(~cat)) {
  320. result = Id::Kind::Invalid;
  321. } else {
  322. result = kind;
  323. }
  324. }
  325. };
  326. // TODO: Patterns should also produce an `InstId`, but currently
  327. // `TuplePattern` produces an `InstBlockId`.
  328. set_id_if_category_is(Parse::NodeCategory::Expr,
  329. Id::KindFor<SemIR::InstId>());
  330. set_id_if_category_is(Parse::NodeCategory::MemberName |
  331. Parse::NodeCategory::NonExprIdentifierName,
  332. Id::KindFor<SemIR::NameId>());
  333. set_id_if_category_is(Parse::NodeCategory::ImplAs,
  334. Id::KindFor<SemIR::InstId>());
  335. set_id_if_category_is(Parse::NodeCategory::Decl |
  336. Parse::NodeCategory::Statement |
  337. Parse::NodeCategory::Modifier,
  338. Id::Kind::None);
  339. return result;
  340. }
  341. // Translate a parse node kind to the enum ID kind it should always
  342. // provide, for the cases where this is not known from the category.
  343. static constexpr auto NodeKindToIdKindSpecialCases(Parse::NodeKind node_kind)
  344. -> std::optional<Id::Kind> {
  345. switch (node_kind) {
  346. case Parse::NodeKind::Addr:
  347. case Parse::NodeKind::CallExprStart:
  348. case Parse::NodeKind::CompileTimeBindingPattern:
  349. case Parse::NodeKind::IfExprThen:
  350. case Parse::NodeKind::LetBindingPattern:
  351. case Parse::NodeKind::ReturnType:
  352. case Parse::NodeKind::ShortCircuitOperandAnd:
  353. case Parse::NodeKind::ShortCircuitOperandOr:
  354. case Parse::NodeKind::StructLiteralField:
  355. case Parse::NodeKind::VarBindingPattern:
  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::ReturnStatementStart:
  394. case Parse::NodeKind::StructLiteralStart:
  395. case Parse::NodeKind::StructTypeLiteralField:
  396. case Parse::NodeKind::StructTypeLiteralStart:
  397. case Parse::NodeKind::TupleLiteralStart:
  398. case Parse::NodeKind::TuplePatternStart:
  399. case Parse::NodeKind::VariableInitializer:
  400. case Parse::NodeKind::VariableIntroducer:
  401. return Id::Kind::None;
  402. case Parse::NodeKind::AdaptIntroducer:
  403. case Parse::NodeKind::AliasInitializer:
  404. case Parse::NodeKind::AliasIntroducer:
  405. case Parse::NodeKind::ArrayExprStart:
  406. case Parse::NodeKind::BaseColon:
  407. case Parse::NodeKind::BaseIntroducer:
  408. case Parse::NodeKind::BreakStatementStart:
  409. case Parse::NodeKind::CallExprComma:
  410. case Parse::NodeKind::ChoiceAlternativeListComma:
  411. case Parse::NodeKind::ChoiceDefinitionStart:
  412. case Parse::NodeKind::ChoiceIntroducer:
  413. case Parse::NodeKind::CodeBlock:
  414. case Parse::NodeKind::ContinueStatementStart:
  415. case Parse::NodeKind::CorePackageName:
  416. case Parse::NodeKind::ExportIntroducer:
  417. case Parse::NodeKind::FileEnd:
  418. case Parse::NodeKind::FileStart:
  419. case Parse::NodeKind::ForHeader:
  420. case Parse::NodeKind::ForHeaderStart:
  421. case Parse::NodeKind::ForIn:
  422. case Parse::NodeKind::IdentifierPackageName:
  423. case Parse::NodeKind::IfConditionStart:
  424. case Parse::NodeKind::ImportIntroducer:
  425. case Parse::NodeKind::IndexExprStart:
  426. case Parse::NodeKind::InvalidParseStart:
  427. case Parse::NodeKind::LibraryIntroducer:
  428. case Parse::NodeKind::LibrarySpecifier:
  429. case Parse::NodeKind::MatchCase:
  430. case Parse::NodeKind::MatchCaseEqualGreater:
  431. case Parse::NodeKind::MatchCaseGuard:
  432. case Parse::NodeKind::MatchCaseGuardIntroducer:
  433. case Parse::NodeKind::MatchCaseGuardStart:
  434. case Parse::NodeKind::MatchCaseIntroducer:
  435. case Parse::NodeKind::MatchCaseStart:
  436. case Parse::NodeKind::MatchCondition:
  437. case Parse::NodeKind::MatchConditionStart:
  438. case Parse::NodeKind::MatchDefault:
  439. case Parse::NodeKind::MatchDefaultEqualGreater:
  440. case Parse::NodeKind::MatchDefaultIntroducer:
  441. case Parse::NodeKind::MatchDefaultStart:
  442. case Parse::NodeKind::MatchIntroducer:
  443. case Parse::NodeKind::MatchStatementStart:
  444. case Parse::NodeKind::NamedConstraintDefinitionStart:
  445. case Parse::NodeKind::NamedConstraintIntroducer:
  446. case Parse::NodeKind::NameQualifierWithParams:
  447. case Parse::NodeKind::NameQualifierWithoutParams:
  448. case Parse::NodeKind::NamespaceStart:
  449. case Parse::NodeKind::PackageIntroducer:
  450. case Parse::NodeKind::ParenExprStart:
  451. case Parse::NodeKind::PatternListComma:
  452. case Parse::NodeKind::Placeholder:
  453. case Parse::NodeKind::RequirementAnd:
  454. case Parse::NodeKind::RequirementEqual:
  455. case Parse::NodeKind::RequirementEqualEqual:
  456. case Parse::NodeKind::RequirementImpls:
  457. case Parse::NodeKind::StructLiteralComma:
  458. case Parse::NodeKind::StructFieldDesignator:
  459. case Parse::NodeKind::StructTypeLiteralComma:
  460. case Parse::NodeKind::Template:
  461. case Parse::NodeKind::TupleLiteralComma:
  462. return Id::Kind::Invalid;
  463. default:
  464. // In this case, the kind must be determinable from the category, or we
  465. // will produce a build error.
  466. return std::nullopt;
  467. }
  468. }
  469. using IdKindTableType = std::array<Id::Kind, Parse::NodeKind::ValidCount>;
  470. // Lookup table to implement `NodeKindToIdKind`. Initialized to the
  471. // return value of `ComputeIdKindTable()`.
  472. static const IdKindTableType IdKindTable;
  473. static consteval auto ComputeIdKindTable() -> IdKindTableType {
  474. IdKindTableType table = {};
  475. auto to_id_kind =
  476. [](const Parse::NodeKind::Definition& node_kind) -> Id::Kind {
  477. if (auto from_category =
  478. NodeCategoryToIdKind(node_kind.category(), true)) {
  479. return *from_category;
  480. }
  481. // Assume any node kind that doesn't have an ID kind from its category nor
  482. // a special case can't appear on the stack just so we can build a table
  483. // and avoid follow-on errors. We'll enforce at compile time that a value
  484. // is actually specified in CheckIdKindTable.
  485. return NodeKindToIdKindSpecialCases(node_kind).value_or(
  486. Id::Kind::Invalid);
  487. };
  488. #define CARBON_PARSE_NODE_KIND(Name) \
  489. table[Parse::Name::Kind.AsInt()] = to_id_kind(Parse::Name::Kind);
  490. #include "toolchain/parse/node_kind.def"
  491. return table;
  492. }
  493. // Check that an Id::Kind is specified for every node kind.
  494. static auto CheckIdKindTable() -> void;
  495. // Translate a parse node kind to the enum ID kind it should always provide.
  496. static constexpr auto NodeKindToIdKind(Parse::NodeKind kind) -> Id::Kind {
  497. return IdKindTable[kind.AsInt()];
  498. }
  499. // Peeks at the ID associated with the top of the name stack.
  500. template <Id::Kind RequiredIdKind>
  501. auto Peek() const -> auto {
  502. Id id = stack_.back().id;
  503. return id.As<RequiredIdKind>();
  504. }
  505. // Pops an entry.
  506. template <typename IdT>
  507. auto PopEntry() -> Entry {
  508. Entry back = stack_.pop_back_val();
  509. CARBON_VLOG("Node Pop {0}: {1} -> {2}\n", stack_.size(),
  510. parse_tree_->node_kind(back.node_id),
  511. back.id.template As<IdT>());
  512. return back;
  513. }
  514. // Pops the top of the stack and returns the node_id and the ID.
  515. template <typename IdT>
  516. auto PopWithNodeId() -> std::pair<Parse::NodeId, IdT> {
  517. Entry back = PopEntry<IdT>();
  518. RequireIdKind(parse_tree_->node_kind(back.node_id), Id::KindFor<IdT>());
  519. return {back.node_id, back.id.template As<IdT>()};
  520. }
  521. // Require a Parse::NodeKind be mapped to a particular Id::Kind.
  522. auto RequireIdKind(Parse::NodeKind parse_kind, Id::Kind id_kind) const
  523. -> void {
  524. CARBON_CHECK(NodeKindToIdKind(parse_kind) == id_kind,
  525. "Unexpected Id::Kind mapping for {0}: expected {1}, found {2}",
  526. parse_kind, SemIR::IdKind(id_kind),
  527. SemIR::IdKind(NodeKindToIdKind(parse_kind)));
  528. }
  529. // Require an entry to have the given Parse::NodeKind.
  530. template <const Parse::NodeKind& RequiredParseKind>
  531. auto RequireParseKind(Parse::NodeId node_id) const -> void {
  532. auto actual_kind = parse_tree_->node_kind(node_id);
  533. CARBON_CHECK(RequiredParseKind == actual_kind, "Expected {0}, found {1}",
  534. RequiredParseKind, actual_kind);
  535. }
  536. // Require an entry to have the given Parse::NodeCategory.
  537. template <Parse::NodeCategory::RawEnumType RequiredParseCategory>
  538. auto RequireParseCategory(Parse::NodeId node_id) const -> void {
  539. auto kind = parse_tree_->node_kind(node_id);
  540. CARBON_CHECK(kind.category().HasAnyOf(RequiredParseCategory),
  541. "Expected {0}, found {1} with category {2}",
  542. RequiredParseCategory, kind, kind.category());
  543. }
  544. // The file's parse tree.
  545. const Parse::Tree* parse_tree_;
  546. // Whether to print verbose output.
  547. llvm::raw_ostream* vlog_stream_;
  548. // The actual stack.
  549. // PushEntry and PopEntry control modification in order to centralize
  550. // vlogging.
  551. llvm::SmallVector<Entry> stack_;
  552. };
  553. constexpr NodeStack::IdKindTableType NodeStack::IdKindTable =
  554. ComputeIdKindTable();
  555. inline auto NodeStack::PopExprWithNodeId()
  556. -> std::pair<Parse::AnyExprId, SemIR::InstId> {
  557. return PopWithNodeId<Parse::NodeCategory::Expr>();
  558. }
  559. inline auto NodeStack::PeekPattern() const -> SemIR::InstId {
  560. return Peek<Id::KindFor<SemIR::InstId>()>();
  561. }
  562. } // namespace Carbon::Check
  563. #endif // CARBON_TOOLCHAIN_CHECK_NODE_STACK_H_