node_stack.h 15 KB

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