node_stack.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 <type_traits>
  7. #include "common/vlog.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/parse/node_kind.h"
  10. #include "toolchain/parse/tree.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. namespace Carbon::Check {
  13. // Wraps the stack of parse nodes for Context. Each parse node can have an
  14. // associated id of some kind (instruction, instruction block, function, class,
  15. // ...).
  16. //
  17. // All pushes and pops will be vlogged.
  18. //
  19. // Pop APIs will run basic verification:
  20. //
  21. // - If receiving a pop_parse_kind, verify that the parse_node being popped is
  22. // of pop_parse_kind.
  23. // - Validates presence of inst_id based on whether it's a solo
  24. // parse_node.
  25. //
  26. // These should be assumed API constraints unless otherwise mentioned on a
  27. // method. The main exception is PopAndIgnore, which doesn't do verification.
  28. class NodeStack {
  29. public:
  30. explicit NodeStack(const Parse::Tree& parse_tree,
  31. llvm::raw_ostream* vlog_stream)
  32. : parse_tree_(&parse_tree), vlog_stream_(vlog_stream) {}
  33. // Pushes a solo parse tree node onto the stack. Used when there is no
  34. // IR generated by the node.
  35. auto Push(Parse::NodeId parse_node) -> void {
  36. auto kind = parse_tree_->node_kind(parse_node);
  37. CARBON_CHECK(ParseNodeKindToIdKind(kind) == IdKind::SoloParseNode)
  38. << "Parse kind expects an Id: " << kind;
  39. CARBON_VLOG() << "Node Push " << stack_.size() << ": " << kind
  40. << " -> <none>\n";
  41. CARBON_CHECK(stack_.size() < (1 << 20))
  42. << "Excessive stack size: likely infinite loop";
  43. stack_.push_back(Entry(parse_node, SemIR::InstId::Invalid));
  44. }
  45. // Pushes a parse tree node onto the stack with an ID.
  46. template <typename IdT>
  47. auto Push(Parse::NodeId parse_node, IdT id) -> void {
  48. auto kind = parse_tree_->node_kind(parse_node);
  49. CARBON_CHECK(ParseNodeKindToIdKind(kind) == IdTypeToIdKind<IdT>())
  50. << "Parse kind expected a different IdT: " << kind << " -> " << id
  51. << "\n";
  52. CARBON_CHECK(id.is_valid()) << "Push called with invalid id: "
  53. << parse_tree_->node_kind(parse_node);
  54. CARBON_VLOG() << "Node Push " << stack_.size() << ": " << kind << " -> "
  55. << id << "\n";
  56. CARBON_CHECK(stack_.size() < (1 << 20))
  57. << "Excessive stack size: likely infinite loop";
  58. stack_.push_back(Entry(parse_node, id));
  59. }
  60. // Returns whether there is a node of the specified kind on top of the stack.
  61. auto PeekIs(Parse::NodeKind kind) const -> bool {
  62. return !stack_.empty() && PeekParseNodeKind() == kind;
  63. }
  64. // Returns whether there is a node of the specified kind on top of the stack.
  65. // Templated for consistency with other functions taking a parse node kind.
  66. template <const Parse::NodeKind& RequiredParseKind>
  67. auto PeekIs() const -> bool {
  68. return PeekIs(RequiredParseKind);
  69. }
  70. // Returns whether there is a name on top of the stack.
  71. auto PeekIsName() const -> bool {
  72. return !stack_.empty() &&
  73. ParseNodeKindToIdKind(PeekParseNodeKind()) == IdKind::NameId;
  74. }
  75. // Pops the top of the stack without any verification.
  76. auto PopAndIgnore() -> void {
  77. Entry back = stack_.pop_back_val();
  78. CARBON_VLOG() << "Node Pop " << stack_.size() << ": "
  79. << parse_tree_->node_kind(back.parse_node)
  80. << " -> <ignored>\n";
  81. }
  82. // Pops the top of the stack and returns the parse_node.
  83. // TODO: return a parse::NodeIdForKind<RequiredParseKind> instead.
  84. template <const Parse::NodeKind& RequiredParseKind>
  85. auto PopForSoloParseNode() -> Parse::NodeId {
  86. Entry back = PopEntry<SemIR::InstId>();
  87. RequireIdKind(RequiredParseKind, IdKind::SoloParseNode);
  88. RequireParseKind<RequiredParseKind>(back.parse_node);
  89. return back.parse_node;
  90. }
  91. // Pops the top of the stack if it is the given kind, and returns the
  92. // parse_node. Otherwise, returns std::nullopt.
  93. // TODO: Return a `Parse::NodeIdForKind<RequiredParseKind>` instead.
  94. template <const Parse::NodeKind& RequiredParseKind>
  95. auto PopForSoloParseNodeIf() -> std::optional<Parse::NodeId> {
  96. if (PeekIs<RequiredParseKind>()) {
  97. return PopForSoloParseNode<RequiredParseKind>();
  98. }
  99. return std::nullopt;
  100. }
  101. // Pops the top of the stack.
  102. template <const Parse::NodeKind& RequiredParseKind>
  103. auto PopAndDiscardSoloParseNode() -> void {
  104. PopForSoloParseNode<RequiredParseKind>();
  105. }
  106. // Pops the top of the stack if it is the given kind. Returns `true` if a node
  107. // was popped.
  108. template <const Parse::NodeKind& RequiredParseKind>
  109. auto PopAndDiscardSoloParseNodeIf() -> bool {
  110. if (!PeekIs<RequiredParseKind>()) {
  111. return false;
  112. }
  113. PopForSoloParseNode<RequiredParseKind>();
  114. return true;
  115. }
  116. // Pops an expression from the top of the stack and returns the parse_node and
  117. // the ID.
  118. auto PopExprWithParseNode() -> std::pair<Parse::NodeId, SemIR::InstId> {
  119. return PopWithParseNode<SemIR::InstId>();
  120. }
  121. // Pops a name from the top of the stack and returns the parse_node and
  122. // the ID.
  123. auto PopNameWithParseNode() -> std::pair<Parse::NodeId, SemIR::NameId> {
  124. return PopWithParseNode<SemIR::NameId>();
  125. }
  126. // Pops the top of the stack and returns the parse_node and the ID.
  127. template <const Parse::NodeKind& RequiredParseKind>
  128. auto PopWithParseNode() -> auto {
  129. constexpr IdKind RequiredIdKind = ParseNodeKindToIdKind(RequiredParseKind);
  130. if constexpr (RequiredIdKind == IdKind::InstId) {
  131. auto back = PopWithParseNode<SemIR::InstId>();
  132. RequireParseKind<RequiredParseKind>(back.first);
  133. return back;
  134. }
  135. if constexpr (RequiredIdKind == IdKind::InstBlockId) {
  136. auto back = PopWithParseNode<SemIR::InstBlockId>();
  137. RequireParseKind<RequiredParseKind>(back.first);
  138. return back;
  139. }
  140. if constexpr (RequiredIdKind == IdKind::FunctionId) {
  141. auto back = PopWithParseNode<SemIR::FunctionId>();
  142. RequireParseKind<RequiredParseKind>(back.first);
  143. return back;
  144. }
  145. if constexpr (RequiredIdKind == IdKind::ClassId) {
  146. auto back = PopWithParseNode<SemIR::ClassId>();
  147. RequireParseKind<RequiredParseKind>(back.first);
  148. return back;
  149. }
  150. if constexpr (RequiredIdKind == IdKind::InterfaceId) {
  151. auto back = PopWithParseNode<SemIR::InterfaceId>();
  152. RequireParseKind<RequiredParseKind>(back.first);
  153. return back;
  154. }
  155. if constexpr (RequiredIdKind == IdKind::NameId) {
  156. auto back = PopWithParseNode<SemIR::NameId>();
  157. RequireParseKind<RequiredParseKind>(back.first);
  158. return back;
  159. }
  160. if constexpr (RequiredIdKind == IdKind::TypeId) {
  161. auto back = PopWithParseNode<SemIR::TypeId>();
  162. RequireParseKind<RequiredParseKind>(back.first);
  163. return back;
  164. }
  165. CARBON_FATAL() << "Unpoppable IdKind for parse kind: " << RequiredParseKind
  166. << "; see value in ParseNodeKindToIdKind";
  167. }
  168. // Pops the top of the stack and returns the parse_node and the ID if it is
  169. // of the specified kind.
  170. template <const Parse::NodeKind& RequiredParseKind>
  171. auto PopWithParseNodeIf()
  172. -> std::optional<decltype(PopWithParseNode<RequiredParseKind>())> {
  173. if (!PeekIs<RequiredParseKind>()) {
  174. return std::nullopt;
  175. }
  176. return PopWithParseNode<RequiredParseKind>();
  177. }
  178. // Pops an expression from the top of the stack and returns the ID.
  179. // Expressions map multiple Parse::NodeKinds to SemIR::InstId always.
  180. auto PopExpr() -> SemIR::InstId { return PopExprWithParseNode().second; }
  181. // Pops a name from the top of the stack and returns the ID.
  182. auto PopName() -> SemIR::NameId { return PopNameWithParseNode().second; }
  183. // TODO: Can we add a `Pop<...>` that takes a parse node category? See
  184. // https://github.com/carbon-language/carbon-lang/pull/3534/files#r1432067519
  185. // Pops the top of the stack and returns the ID.
  186. template <const Parse::NodeKind& RequiredParseKind>
  187. auto Pop() -> auto {
  188. return PopWithParseNode<RequiredParseKind>().second;
  189. }
  190. // Pops the top of the stack if it has the given kind, and returns the ID.
  191. // Otherwise returns std::nullopt.
  192. template <const Parse::NodeKind& RequiredParseKind>
  193. auto PopIf() -> std::optional<decltype(Pop<RequiredParseKind>())> {
  194. if (PeekIs<RequiredParseKind>()) {
  195. return Pop<RequiredParseKind>();
  196. }
  197. return std::nullopt;
  198. }
  199. // Peeks at the parse node of the top of the node stack.
  200. auto PeekParseNode() const -> Parse::NodeId {
  201. return stack_.back().parse_node;
  202. }
  203. // Peeks at the kind of the parse node of the top of the node stack.
  204. auto PeekParseNodeKind() const -> Parse::NodeKind {
  205. return parse_tree_->node_kind(PeekParseNode());
  206. }
  207. // Peeks at the ID associated with the top of the name stack.
  208. template <const Parse::NodeKind& RequiredParseKind>
  209. auto Peek() const -> auto {
  210. Entry back = stack_.back();
  211. RequireParseKind<RequiredParseKind>(back.parse_node);
  212. constexpr IdKind RequiredIdKind = ParseNodeKindToIdKind(RequiredParseKind);
  213. if constexpr (RequiredIdKind == IdKind::InstId) {
  214. return back.id<SemIR::InstId>();
  215. }
  216. if constexpr (RequiredIdKind == IdKind::InstBlockId) {
  217. return back.id<SemIR::InstBlockId>();
  218. }
  219. if constexpr (RequiredIdKind == IdKind::FunctionId) {
  220. return back.id<SemIR::FunctionId>();
  221. }
  222. if constexpr (RequiredIdKind == IdKind::ClassId) {
  223. return back.id<SemIR::ClassId>();
  224. }
  225. if constexpr (RequiredIdKind == IdKind::InterfaceId) {
  226. return back.id<SemIR::InterfaceId>();
  227. }
  228. if constexpr (RequiredIdKind == IdKind::NameId) {
  229. return back.id<SemIR::NameId>();
  230. }
  231. if constexpr (RequiredIdKind == IdKind::TypeId) {
  232. return back.id<SemIR::TypeId>();
  233. }
  234. CARBON_FATAL() << "Unpeekable IdKind for parse kind: " << RequiredParseKind
  235. << "; see value in ParseNodeKindToIdKind";
  236. }
  237. // Prints the stack for a stack dump.
  238. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  239. auto empty() const -> bool { return stack_.empty(); }
  240. auto size() const -> size_t { return stack_.size(); }
  241. private:
  242. // Possible associated ID types.
  243. enum class IdKind : int8_t {
  244. InstId,
  245. InstBlockId,
  246. FunctionId,
  247. ClassId,
  248. InterfaceId,
  249. NameId,
  250. TypeId,
  251. // No associated ID type.
  252. SoloParseNode,
  253. // Not expected in the node stack.
  254. Unused,
  255. };
  256. // An entry in stack_.
  257. struct Entry {
  258. explicit Entry(Parse::NodeId parse_node, SemIR::InstId inst_id)
  259. : parse_node(parse_node), inst_id(inst_id) {}
  260. explicit Entry(Parse::NodeId parse_node, SemIR::InstBlockId inst_block_id)
  261. : parse_node(parse_node), inst_block_id(inst_block_id) {}
  262. explicit Entry(Parse::NodeId parse_node, SemIR::FunctionId function_id)
  263. : parse_node(parse_node), function_id(function_id) {}
  264. explicit Entry(Parse::NodeId parse_node, SemIR::ClassId class_id)
  265. : parse_node(parse_node), class_id(class_id) {}
  266. explicit Entry(Parse::NodeId parse_node, SemIR::InterfaceId interface_id)
  267. : parse_node(parse_node), interface_id(interface_id) {}
  268. explicit Entry(Parse::NodeId parse_node, SemIR::NameId name_id)
  269. : parse_node(parse_node), name_id(name_id) {}
  270. explicit Entry(Parse::NodeId parse_node, SemIR::TypeId type_id)
  271. : parse_node(parse_node), type_id(type_id) {}
  272. // Returns the appropriate ID basaed on type.
  273. template <typename T>
  274. auto id() -> T& {
  275. if constexpr (std::is_same<T, SemIR::InstId>()) {
  276. return inst_id;
  277. }
  278. if constexpr (std::is_same<T, SemIR::InstBlockId>()) {
  279. return inst_block_id;
  280. }
  281. if constexpr (std::is_same<T, SemIR::FunctionId>()) {
  282. return function_id;
  283. }
  284. if constexpr (std::is_same<T, SemIR::ClassId>()) {
  285. return class_id;
  286. }
  287. if constexpr (std::is_same<T, SemIR::InterfaceId>()) {
  288. return interface_id;
  289. }
  290. if constexpr (std::is_same<T, SemIR::NameId>()) {
  291. return name_id;
  292. }
  293. if constexpr (std::is_same<T, SemIR::TypeId>()) {
  294. return type_id;
  295. }
  296. }
  297. // The parse node associated with the stack entry.
  298. Parse::NodeId parse_node;
  299. // The entries will evaluate as invalid if and only if they're a solo
  300. // parse_node. Invalid is used instead of optional to save space.
  301. //
  302. // A discriminator isn't needed because the caller can determine which field
  303. // is used based on the Parse::NodeKind.
  304. union {
  305. SemIR::InstId inst_id;
  306. SemIR::InstBlockId inst_block_id;
  307. SemIR::FunctionId function_id;
  308. SemIR::ClassId class_id;
  309. SemIR::InterfaceId interface_id;
  310. SemIR::NameId name_id;
  311. SemIR::TypeId type_id;
  312. };
  313. };
  314. static_assert(sizeof(Entry) == 8, "Unexpected Entry size");
  315. // Translate a parse node kind to the enum ID kind it should always provide.
  316. static constexpr auto ParseNodeKindToIdKind(Parse::NodeKind kind) -> IdKind {
  317. switch (kind) {
  318. case Parse::NodeKind::Address:
  319. case Parse::NodeKind::ArrayExpr:
  320. case Parse::NodeKind::BindingPattern:
  321. case Parse::NodeKind::CallExpr:
  322. case Parse::NodeKind::CallExprStart:
  323. case Parse::NodeKind::IdentifierNameExpr:
  324. case Parse::NodeKind::IfExprThen:
  325. case Parse::NodeKind::IfExprElse:
  326. case Parse::NodeKind::IndexExpr:
  327. case Parse::NodeKind::MemberAccessExpr:
  328. case Parse::NodeKind::PackageExpr:
  329. case Parse::NodeKind::ParenExpr:
  330. case Parse::NodeKind::ReturnType:
  331. case Parse::NodeKind::SelfTypeNameExpr:
  332. case Parse::NodeKind::SelfValueNameExpr:
  333. case Parse::NodeKind::ShortCircuitOperandAnd:
  334. case Parse::NodeKind::ShortCircuitOperandOr:
  335. case Parse::NodeKind::ShortCircuitOperatorAnd:
  336. case Parse::NodeKind::ShortCircuitOperatorOr:
  337. case Parse::NodeKind::StructFieldValue:
  338. case Parse::NodeKind::StructLiteral:
  339. case Parse::NodeKind::StructFieldType:
  340. case Parse::NodeKind::StructTypeLiteral:
  341. case Parse::NodeKind::TupleLiteral:
  342. return IdKind::InstId;
  343. case Parse::NodeKind::IfCondition:
  344. case Parse::NodeKind::IfExprIf:
  345. case Parse::NodeKind::ImplicitParamList:
  346. case Parse::NodeKind::TuplePattern:
  347. case Parse::NodeKind::WhileCondition:
  348. case Parse::NodeKind::WhileConditionStart:
  349. return IdKind::InstBlockId;
  350. case Parse::NodeKind::FunctionDefinitionStart:
  351. return IdKind::FunctionId;
  352. case Parse::NodeKind::ClassDefinitionStart:
  353. return IdKind::ClassId;
  354. case Parse::NodeKind::InterfaceDefinitionStart:
  355. return IdKind::InterfaceId;
  356. case Parse::NodeKind::BaseName:
  357. case Parse::NodeKind::IdentifierName:
  358. case Parse::NodeKind::SelfValueName:
  359. return IdKind::NameId;
  360. case Parse::NodeKind::ArrayExprSemi:
  361. case Parse::NodeKind::ClassIntroducer:
  362. case Parse::NodeKind::CodeBlockStart:
  363. case Parse::NodeKind::ExprOpenParen:
  364. case Parse::NodeKind::FunctionIntroducer:
  365. case Parse::NodeKind::IfStatementElse:
  366. case Parse::NodeKind::ImplicitParamListStart:
  367. case Parse::NodeKind::InterfaceIntroducer:
  368. case Parse::NodeKind::LetIntroducer:
  369. case Parse::NodeKind::QualifiedDecl:
  370. case Parse::NodeKind::ReturnedModifier:
  371. case Parse::NodeKind::ReturnStatementStart:
  372. case Parse::NodeKind::ReturnVarModifier:
  373. case Parse::NodeKind::StructLiteralOrStructTypeLiteralStart:
  374. case Parse::NodeKind::TuplePatternStart:
  375. case Parse::NodeKind::VariableInitializer:
  376. case Parse::NodeKind::VariableIntroducer:
  377. return IdKind::SoloParseNode;
  378. // Use x-macros to handle boilerplate cases.
  379. #define CARBON_PARSE_NODE_KIND(...)
  380. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  381. case Parse::NodeKind::InfixOperator##Name: \
  382. return IdKind::InstId;
  383. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  384. case Parse::NodeKind::PostfixOperator##Name: \
  385. return IdKind::InstId;
  386. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  387. case Parse::NodeKind::PrefixOperator##Name: \
  388. return IdKind::InstId;
  389. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, ...) \
  390. case Parse::NodeKind::Name: \
  391. return IdKind::InstId;
  392. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  393. case Parse::NodeKind::Name##Modifier: \
  394. return IdKind::SoloParseNode;
  395. #include "toolchain/parse/node_kind.def"
  396. default:
  397. return IdKind::Unused;
  398. }
  399. }
  400. // Translates an ID type to the enum ID kind for comparison with
  401. // ParseNodeKindToIdKind.
  402. template <typename IdT>
  403. static constexpr auto IdTypeToIdKind() -> IdKind {
  404. if constexpr (std::is_same_v<IdT, SemIR::InstId>) {
  405. return IdKind::InstId;
  406. }
  407. if constexpr (std::is_same_v<IdT, SemIR::InstBlockId>) {
  408. return IdKind::InstBlockId;
  409. }
  410. if constexpr (std::is_same_v<IdT, SemIR::FunctionId>) {
  411. return IdKind::FunctionId;
  412. }
  413. if constexpr (std::is_same_v<IdT, SemIR::ClassId>) {
  414. return IdKind::ClassId;
  415. }
  416. if constexpr (std::is_same_v<IdT, SemIR::InterfaceId>) {
  417. return IdKind::InterfaceId;
  418. }
  419. if constexpr (std::is_same_v<IdT, SemIR::NameId>) {
  420. return IdKind::NameId;
  421. }
  422. if constexpr (std::is_same_v<IdT, SemIR::TypeId>) {
  423. return IdKind::TypeId;
  424. }
  425. }
  426. // Pops an entry.
  427. template <typename IdT>
  428. auto PopEntry() -> Entry {
  429. Entry back = stack_.pop_back_val();
  430. CARBON_VLOG() << "Node Pop " << stack_.size() << ": "
  431. << parse_tree_->node_kind(back.parse_node) << " -> "
  432. << back.id<IdT>() << "\n";
  433. return back;
  434. }
  435. // Pops the top of the stack and returns the parse_node and the ID.
  436. template <typename IdT>
  437. auto PopWithParseNode() -> std::pair<Parse::NodeId, IdT> {
  438. Entry back = PopEntry<IdT>();
  439. RequireIdKind(parse_tree_->node_kind(back.parse_node),
  440. IdTypeToIdKind<IdT>());
  441. return {back.parse_node, back.id<IdT>()};
  442. }
  443. // Require a Parse::NodeKind be mapped to a particular IdKind.
  444. auto RequireIdKind(Parse::NodeKind parse_kind, IdKind id_kind) const -> void {
  445. CARBON_CHECK(ParseNodeKindToIdKind(parse_kind) == id_kind)
  446. << "Unexpected IdKind mapping for " << parse_kind;
  447. }
  448. // Require an entry to have the given Parse::NodeKind.
  449. template <const Parse::NodeKind& RequiredParseKind>
  450. auto RequireParseKind(Parse::NodeId parse_node) const -> void {
  451. auto actual_kind = parse_tree_->node_kind(parse_node);
  452. CARBON_CHECK(RequiredParseKind == actual_kind)
  453. << "Expected " << RequiredParseKind << ", found " << actual_kind;
  454. }
  455. // The file's parse tree.
  456. const Parse::Tree* parse_tree_;
  457. // Whether to print verbose output.
  458. llvm::raw_ostream* vlog_stream_;
  459. // The actual stack.
  460. // PushEntry and PopEntry control modification in order to centralize
  461. // vlogging.
  462. llvm::SmallVector<Entry> stack_;
  463. };
  464. } // namespace Carbon::Check
  465. #endif // CARBON_TOOLCHAIN_CHECK_NODE_STACK_H_