node_stack.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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::Node parse_node) -> void {
  36. CARBON_CHECK(ParseNodeKindToIdKind(parse_tree_->node_kind(parse_node)) ==
  37. IdKind::SoloParseNode)
  38. << "Parse kind expects an Id: " << parse_tree_->node_kind(parse_node);
  39. CARBON_VLOG() << "Node Push " << stack_.size() << ": "
  40. << parse_tree_->node_kind(parse_node) << " -> <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::Node parse_node, IdT id) -> void {
  48. CARBON_CHECK(ParseNodeKindToIdKind(parse_tree_->node_kind(parse_node)) ==
  49. IdTypeToIdKind<IdT>())
  50. << "Parse kind expected a different IdT: "
  51. << parse_tree_->node_kind(parse_node) << " -> " << id << "\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() << ": "
  55. << parse_tree_->node_kind(parse_node) << " -> " << 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 the node on the top of the stack is the specified kind.
  61. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  62. auto PeekIs() const -> bool {
  63. return parse_tree_->node_kind(PeekParseNode()) == RequiredParseKind;
  64. }
  65. // Pops the top of the stack without any verification.
  66. auto PopAndIgnore() -> void { PopEntry<SemIR::InstId>(); }
  67. // Pops the top of the stack and returns the parse_node.
  68. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  69. auto PopForSoloParseNode() -> Parse::Node {
  70. Entry back = PopEntry<SemIR::InstId>();
  71. RequireIdKind(Parse::NodeKind::Create(RequiredParseKind),
  72. IdKind::SoloParseNode);
  73. RequireParseKind<RequiredParseKind>(back.parse_node);
  74. return back.parse_node;
  75. }
  76. // Pops the top of the stack if it is the given kind, and returns the
  77. // parse_node. Otherwise, returns std::nullopt.
  78. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  79. auto PopForSoloParseNodeIf() -> std::optional<Parse::Node> {
  80. if (PeekIs<RequiredParseKind>()) {
  81. return PopForSoloParseNode<RequiredParseKind>();
  82. }
  83. return std::nullopt;
  84. }
  85. // Pops the top of the stack.
  86. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  87. auto PopAndDiscardSoloParseNode() -> void {
  88. PopForSoloParseNode<RequiredParseKind>();
  89. }
  90. // Pops the top of the stack if it is the given kind. Returns `true` if a node
  91. // was popped.
  92. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  93. auto PopAndDiscardSoloParseNodeIf() -> bool {
  94. if (!PeekIs<RequiredParseKind>()) {
  95. return false;
  96. }
  97. PopForSoloParseNode<RequiredParseKind>();
  98. return true;
  99. }
  100. // Pops an expression from the top of the stack and returns the parse_node and
  101. // the ID.
  102. auto PopExprWithParseNode() -> std::pair<Parse::Node, SemIR::InstId> {
  103. return PopWithParseNode<SemIR::InstId>();
  104. }
  105. // Pops the top of the stack and returns the parse_node and the ID.
  106. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  107. auto PopWithParseNode() -> auto {
  108. constexpr IdKind RequiredIdKind =
  109. ParseNodeKindToIdKind(Parse::NodeKind::Create(RequiredParseKind));
  110. if constexpr (RequiredIdKind == IdKind::InstId) {
  111. auto back = PopWithParseNode<SemIR::InstId>();
  112. RequireParseKind<RequiredParseKind>(back.first);
  113. return back;
  114. }
  115. if constexpr (RequiredIdKind == IdKind::InstBlockId) {
  116. auto back = PopWithParseNode<SemIR::InstBlockId>();
  117. RequireParseKind<RequiredParseKind>(back.first);
  118. return back;
  119. }
  120. if constexpr (RequiredIdKind == IdKind::FunctionId) {
  121. auto back = PopWithParseNode<SemIR::FunctionId>();
  122. RequireParseKind<RequiredParseKind>(back.first);
  123. return back;
  124. }
  125. if constexpr (RequiredIdKind == IdKind::ClassId) {
  126. auto back = PopWithParseNode<SemIR::ClassId>();
  127. RequireParseKind<RequiredParseKind>(back.first);
  128. return back;
  129. }
  130. if constexpr (RequiredIdKind == IdKind::NameId) {
  131. auto back = PopWithParseNode<SemIR::NameId>();
  132. RequireParseKind<RequiredParseKind>(back.first);
  133. return back;
  134. }
  135. if constexpr (RequiredIdKind == IdKind::TypeId) {
  136. auto back = PopWithParseNode<SemIR::TypeId>();
  137. RequireParseKind<RequiredParseKind>(back.first);
  138. return back;
  139. }
  140. CARBON_FATAL() << "Unpoppable IdKind for parse kind: "
  141. << Parse::NodeKind::Create(RequiredParseKind)
  142. << "; see value in ParseNodeKindToIdKind";
  143. }
  144. // Pops an expression from the top of the stack and returns the ID.
  145. // Expressions map multiple Parse::NodeKinds to SemIR::InstId always.
  146. auto PopExpr() -> SemIR::InstId { return PopExprWithParseNode().second; }
  147. // Pops the top of the stack and returns the ID.
  148. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  149. auto Pop() -> auto {
  150. return PopWithParseNode<RequiredParseKind>().second;
  151. }
  152. // Pops the top of the stack if it has the given kind, and returns the ID.
  153. // Otherwise returns std::nullopt.
  154. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  155. auto PopIf() -> std::optional<decltype(Pop<RequiredParseKind>())> {
  156. if (PeekIs<RequiredParseKind>()) {
  157. return Pop<RequiredParseKind>();
  158. }
  159. return std::nullopt;
  160. }
  161. // Peeks at the parse node of the top of the name stack.
  162. auto PeekParseNode() const -> Parse::Node { return stack_.back().parse_node; }
  163. // Peeks at the ID associated with the top of the name stack.
  164. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  165. auto Peek() const -> auto {
  166. Entry back = stack_.back();
  167. RequireParseKind<RequiredParseKind>(back.parse_node);
  168. constexpr IdKind RequiredIdKind =
  169. ParseNodeKindToIdKind(Parse::NodeKind::Create(RequiredParseKind));
  170. if constexpr (RequiredIdKind == IdKind::InstId) {
  171. return back.id<SemIR::InstId>();
  172. }
  173. if constexpr (RequiredIdKind == IdKind::InstBlockId) {
  174. return back.id<SemIR::InstBlockId>();
  175. }
  176. if constexpr (RequiredIdKind == IdKind::FunctionId) {
  177. return back.id<SemIR::FunctionId>();
  178. }
  179. if constexpr (RequiredIdKind == IdKind::ClassId) {
  180. return back.id<SemIR::ClassId>();
  181. }
  182. if constexpr (RequiredIdKind == IdKind::NameId) {
  183. return back.id<SemIR::NameId>();
  184. }
  185. if constexpr (RequiredIdKind == IdKind::TypeId) {
  186. return back.id<SemIR::TypeId>();
  187. }
  188. CARBON_FATAL() << "Unpeekable IdKind for parse kind: "
  189. << Parse::NodeKind::Create(RequiredParseKind)
  190. << "; see value in ParseNodeKindToIdKind";
  191. }
  192. // Prints the stack for a stack dump.
  193. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  194. auto empty() const -> bool { return stack_.empty(); }
  195. auto size() const -> size_t { return stack_.size(); }
  196. private:
  197. // Possible associated ID types.
  198. enum class IdKind : int8_t {
  199. InstId,
  200. InstBlockId,
  201. FunctionId,
  202. ClassId,
  203. NameId,
  204. TypeId,
  205. // No associated ID type.
  206. SoloParseNode,
  207. // Not expected in the node stack.
  208. Unused,
  209. };
  210. // An entry in stack_.
  211. struct Entry {
  212. explicit Entry(Parse::Node parse_node, SemIR::InstId inst_id)
  213. : parse_node(parse_node), inst_id(inst_id) {}
  214. explicit Entry(Parse::Node parse_node, SemIR::InstBlockId inst_block_id)
  215. : parse_node(parse_node), inst_block_id(inst_block_id) {}
  216. explicit Entry(Parse::Node parse_node, SemIR::FunctionId function_id)
  217. : parse_node(parse_node), function_id(function_id) {}
  218. explicit Entry(Parse::Node parse_node, SemIR::ClassId class_id)
  219. : parse_node(parse_node), class_id(class_id) {}
  220. explicit Entry(Parse::Node parse_node, SemIR::NameId name_id)
  221. : parse_node(parse_node), name_id(name_id) {}
  222. explicit Entry(Parse::Node parse_node, SemIR::TypeId type_id)
  223. : parse_node(parse_node), type_id(type_id) {}
  224. // Returns the appropriate ID basaed on type.
  225. template <typename T>
  226. auto id() -> T& {
  227. if constexpr (std::is_same<T, SemIR::InstId>()) {
  228. return inst_id;
  229. }
  230. if constexpr (std::is_same<T, SemIR::InstBlockId>()) {
  231. return inst_block_id;
  232. }
  233. if constexpr (std::is_same<T, SemIR::FunctionId>()) {
  234. return function_id;
  235. }
  236. if constexpr (std::is_same<T, SemIR::ClassId>()) {
  237. return class_id;
  238. }
  239. if constexpr (std::is_same<T, SemIR::NameId>()) {
  240. return name_id;
  241. }
  242. if constexpr (std::is_same<T, SemIR::TypeId>()) {
  243. return type_id;
  244. }
  245. }
  246. // The parse node associated with the stack entry.
  247. Parse::Node parse_node;
  248. // The entries will evaluate as invalid if and only if they're a solo
  249. // parse_node. Invalid is used instead of optional to save space.
  250. //
  251. // A discriminator isn't needed because the caller can determine which field
  252. // is used based on the Parse::NodeKind.
  253. union {
  254. SemIR::InstId inst_id;
  255. SemIR::InstBlockId inst_block_id;
  256. SemIR::FunctionId function_id;
  257. SemIR::ClassId class_id;
  258. SemIR::NameId name_id;
  259. SemIR::TypeId type_id;
  260. };
  261. };
  262. static_assert(sizeof(Entry) == 8, "Unexpected Entry size");
  263. // Translate a parse node kind to the enum ID kind it should always provide.
  264. static constexpr auto ParseNodeKindToIdKind(Parse::NodeKind kind) -> IdKind {
  265. switch (kind) {
  266. case Parse::NodeKind::ArrayExpr:
  267. case Parse::NodeKind::CallExpr:
  268. case Parse::NodeKind::CallExprStart:
  269. case Parse::NodeKind::IfExprThen:
  270. case Parse::NodeKind::IfExprElse:
  271. case Parse::NodeKind::IndexExpr:
  272. case Parse::NodeKind::InfixOperator:
  273. case Parse::NodeKind::Literal:
  274. case Parse::NodeKind::MemberAccessExpr:
  275. case Parse::NodeKind::NameExpr:
  276. case Parse::NodeKind::ParenExpr:
  277. case Parse::NodeKind::PatternBinding:
  278. case Parse::NodeKind::PostfixOperator:
  279. case Parse::NodeKind::PrefixOperator:
  280. case Parse::NodeKind::ReturnType:
  281. case Parse::NodeKind::SelfTypeNameExpr:
  282. case Parse::NodeKind::SelfValueNameExpr:
  283. case Parse::NodeKind::ShortCircuitOperand:
  284. case Parse::NodeKind::StructFieldValue:
  285. case Parse::NodeKind::StructLiteral:
  286. case Parse::NodeKind::StructFieldType:
  287. case Parse::NodeKind::StructTypeLiteral:
  288. case Parse::NodeKind::TupleLiteral:
  289. return IdKind::InstId;
  290. case Parse::NodeKind::IfCondition:
  291. case Parse::NodeKind::IfExprIf:
  292. case Parse::NodeKind::ImplicitParamList:
  293. case Parse::NodeKind::ParamList:
  294. case Parse::NodeKind::WhileCondition:
  295. case Parse::NodeKind::WhileConditionStart:
  296. return IdKind::InstBlockId;
  297. case Parse::NodeKind::FunctionDefinitionStart:
  298. return IdKind::FunctionId;
  299. case Parse::NodeKind::ClassDefinitionStart:
  300. return IdKind::ClassId;
  301. case Parse::NodeKind::Name:
  302. return IdKind::NameId;
  303. case Parse::NodeKind::AbstractModifier:
  304. case Parse::NodeKind::ArrayExprSemi:
  305. case Parse::NodeKind::BaseModifier:
  306. case Parse::NodeKind::ClassIntroducer:
  307. case Parse::NodeKind::CodeBlockStart:
  308. case Parse::NodeKind::FunctionIntroducer:
  309. case Parse::NodeKind::IfStatementElse:
  310. case Parse::NodeKind::ImplicitParamListStart:
  311. case Parse::NodeKind::LetIntroducer:
  312. case Parse::NodeKind::ParamListStart:
  313. case Parse::NodeKind::ParenExprOrTupleLiteralStart:
  314. case Parse::NodeKind::QualifiedDecl:
  315. case Parse::NodeKind::ReturnedModifier:
  316. case Parse::NodeKind::ReturnStatementStart:
  317. case Parse::NodeKind::ReturnVarModifier:
  318. case Parse::NodeKind::SelfValueName:
  319. case Parse::NodeKind::StructLiteralOrStructTypeLiteralStart:
  320. case Parse::NodeKind::VariableInitializer:
  321. case Parse::NodeKind::VariableIntroducer:
  322. return IdKind::SoloParseNode;
  323. default:
  324. return IdKind::Unused;
  325. }
  326. }
  327. // Translates an ID type to the enum ID kind for comparison with
  328. // ParseNodeKindToIdKind.
  329. template <typename IdT>
  330. static constexpr auto IdTypeToIdKind() -> IdKind {
  331. if constexpr (std::is_same_v<IdT, SemIR::InstId>) {
  332. return IdKind::InstId;
  333. }
  334. if constexpr (std::is_same_v<IdT, SemIR::InstBlockId>) {
  335. return IdKind::InstBlockId;
  336. }
  337. if constexpr (std::is_same_v<IdT, SemIR::FunctionId>) {
  338. return IdKind::FunctionId;
  339. }
  340. if constexpr (std::is_same_v<IdT, SemIR::ClassId>) {
  341. return IdKind::ClassId;
  342. }
  343. if constexpr (std::is_same_v<IdT, SemIR::NameId>) {
  344. return IdKind::NameId;
  345. }
  346. if constexpr (std::is_same_v<IdT, SemIR::TypeId>) {
  347. return IdKind::TypeId;
  348. }
  349. }
  350. // Pops an entry.
  351. template <typename IdT>
  352. auto PopEntry() -> Entry {
  353. Entry back = stack_.pop_back_val();
  354. CARBON_VLOG() << "Node Pop " << stack_.size() << ": "
  355. << parse_tree_->node_kind(back.parse_node) << " -> "
  356. << back.id<IdT>() << "\n";
  357. return back;
  358. }
  359. // Pops the top of the stack and returns the parse_node and the ID.
  360. template <typename IdT>
  361. auto PopWithParseNode() -> std::pair<Parse::Node, IdT> {
  362. Entry back = PopEntry<IdT>();
  363. RequireIdKind(parse_tree_->node_kind(back.parse_node),
  364. IdTypeToIdKind<IdT>());
  365. return {back.parse_node, back.id<IdT>()};
  366. }
  367. // Require a Parse::NodeKind be mapped to a particular IdKind.
  368. auto RequireIdKind(Parse::NodeKind parse_kind, IdKind id_kind) const -> void {
  369. CARBON_CHECK(ParseNodeKindToIdKind(parse_kind) == id_kind)
  370. << "Unexpected IdKind mapping for " << parse_kind;
  371. }
  372. // Require an entry to have the given Parse::NodeKind.
  373. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  374. auto RequireParseKind(Parse::Node parse_node) const -> void {
  375. auto actual_kind = parse_tree_->node_kind(parse_node);
  376. CARBON_CHECK(RequiredParseKind == actual_kind)
  377. << "Expected " << Parse::NodeKind::Create(RequiredParseKind)
  378. << ", found " << actual_kind;
  379. }
  380. // The file's parse tree.
  381. const Parse::Tree* parse_tree_;
  382. // Whether to print verbose output.
  383. llvm::raw_ostream* vlog_stream_;
  384. // The actual stack.
  385. // PushEntry and PopEntry control modification in order to centralize
  386. // vlogging.
  387. llvm::SmallVector<Entry> stack_;
  388. };
  389. } // namespace Carbon::Check
  390. #endif // CARBON_TOOLCHAIN_CHECK_NODE_STACK_H_