node_stack.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. 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::NodeId 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::NodeId {
  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::NodeId> {
  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::NodeId, 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::NodeId {
  163. return stack_.back().parse_node;
  164. }
  165. // Peeks at the ID associated with the top of the name stack.
  166. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  167. auto Peek() const -> auto {
  168. Entry back = stack_.back();
  169. RequireParseKind<RequiredParseKind>(back.parse_node);
  170. constexpr IdKind RequiredIdKind =
  171. ParseNodeKindToIdKind(Parse::NodeKind::Create(RequiredParseKind));
  172. if constexpr (RequiredIdKind == IdKind::InstId) {
  173. return back.id<SemIR::InstId>();
  174. }
  175. if constexpr (RequiredIdKind == IdKind::InstBlockId) {
  176. return back.id<SemIR::InstBlockId>();
  177. }
  178. if constexpr (RequiredIdKind == IdKind::FunctionId) {
  179. return back.id<SemIR::FunctionId>();
  180. }
  181. if constexpr (RequiredIdKind == IdKind::ClassId) {
  182. return back.id<SemIR::ClassId>();
  183. }
  184. if constexpr (RequiredIdKind == IdKind::NameId) {
  185. return back.id<SemIR::NameId>();
  186. }
  187. if constexpr (RequiredIdKind == IdKind::TypeId) {
  188. return back.id<SemIR::TypeId>();
  189. }
  190. CARBON_FATAL() << "Unpeekable IdKind for parse kind: "
  191. << Parse::NodeKind::Create(RequiredParseKind)
  192. << "; see value in ParseNodeKindToIdKind";
  193. }
  194. // Prints the stack for a stack dump.
  195. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  196. auto empty() const -> bool { return stack_.empty(); }
  197. auto size() const -> size_t { return stack_.size(); }
  198. private:
  199. // Possible associated ID types.
  200. enum class IdKind : int8_t {
  201. InstId,
  202. InstBlockId,
  203. FunctionId,
  204. ClassId,
  205. NameId,
  206. TypeId,
  207. // No associated ID type.
  208. SoloParseNode,
  209. // Not expected in the node stack.
  210. Unused,
  211. };
  212. // An entry in stack_.
  213. struct Entry {
  214. explicit Entry(Parse::NodeId parse_node, SemIR::InstId inst_id)
  215. : parse_node(parse_node), inst_id(inst_id) {}
  216. explicit Entry(Parse::NodeId parse_node, SemIR::InstBlockId inst_block_id)
  217. : parse_node(parse_node), inst_block_id(inst_block_id) {}
  218. explicit Entry(Parse::NodeId parse_node, SemIR::FunctionId function_id)
  219. : parse_node(parse_node), function_id(function_id) {}
  220. explicit Entry(Parse::NodeId parse_node, SemIR::ClassId class_id)
  221. : parse_node(parse_node), class_id(class_id) {}
  222. explicit Entry(Parse::NodeId parse_node, SemIR::NameId name_id)
  223. : parse_node(parse_node), name_id(name_id) {}
  224. explicit Entry(Parse::NodeId parse_node, SemIR::TypeId type_id)
  225. : parse_node(parse_node), type_id(type_id) {}
  226. // Returns the appropriate ID basaed on type.
  227. template <typename T>
  228. auto id() -> T& {
  229. if constexpr (std::is_same<T, SemIR::InstId>()) {
  230. return inst_id;
  231. }
  232. if constexpr (std::is_same<T, SemIR::InstBlockId>()) {
  233. return inst_block_id;
  234. }
  235. if constexpr (std::is_same<T, SemIR::FunctionId>()) {
  236. return function_id;
  237. }
  238. if constexpr (std::is_same<T, SemIR::ClassId>()) {
  239. return class_id;
  240. }
  241. if constexpr (std::is_same<T, SemIR::NameId>()) {
  242. return name_id;
  243. }
  244. if constexpr (std::is_same<T, SemIR::TypeId>()) {
  245. return type_id;
  246. }
  247. }
  248. // The parse node associated with the stack entry.
  249. Parse::NodeId parse_node;
  250. // The entries will evaluate as invalid if and only if they're a solo
  251. // parse_node. Invalid is used instead of optional to save space.
  252. //
  253. // A discriminator isn't needed because the caller can determine which field
  254. // is used based on the Parse::NodeKind.
  255. union {
  256. SemIR::InstId inst_id;
  257. SemIR::InstBlockId inst_block_id;
  258. SemIR::FunctionId function_id;
  259. SemIR::ClassId class_id;
  260. SemIR::NameId name_id;
  261. SemIR::TypeId type_id;
  262. };
  263. };
  264. static_assert(sizeof(Entry) == 8, "Unexpected Entry size");
  265. // Translate a parse node kind to the enum ID kind it should always provide.
  266. static constexpr auto ParseNodeKindToIdKind(Parse::NodeKind kind) -> IdKind {
  267. switch (kind) {
  268. case Parse::NodeKind::ArrayExpr:
  269. case Parse::NodeKind::BindingPattern:
  270. case Parse::NodeKind::CallExpr:
  271. case Parse::NodeKind::CallExprStart:
  272. case Parse::NodeKind::IfExprThen:
  273. case Parse::NodeKind::IfExprElse:
  274. case Parse::NodeKind::IndexExpr:
  275. case Parse::NodeKind::InfixOperator:
  276. case Parse::NodeKind::MemberAccessExpr:
  277. case Parse::NodeKind::NameExpr:
  278. case Parse::NodeKind::PackageExpr:
  279. case Parse::NodeKind::ParenExpr:
  280. case Parse::NodeKind::PostfixOperator:
  281. case Parse::NodeKind::PrefixOperator:
  282. case Parse::NodeKind::ReturnType:
  283. case Parse::NodeKind::SelfTypeNameExpr:
  284. case Parse::NodeKind::SelfValueNameExpr:
  285. case Parse::NodeKind::ShortCircuitOperand:
  286. case Parse::NodeKind::StructFieldValue:
  287. case Parse::NodeKind::StructLiteral:
  288. case Parse::NodeKind::StructFieldType:
  289. case Parse::NodeKind::StructTypeLiteral:
  290. case Parse::NodeKind::TupleLiteral:
  291. // Use x-macros to handle literal cases.
  292. #define CARBON_PARSE_NODE_KIND(...)
  293. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, ...) \
  294. case Parse::NodeKind::Name:
  295. #include "toolchain/parse/node_kind.def"
  296. return IdKind::InstId;
  297. case Parse::NodeKind::IfCondition:
  298. case Parse::NodeKind::IfExprIf:
  299. case Parse::NodeKind::ImplicitParamList:
  300. case Parse::NodeKind::ParamList:
  301. case Parse::NodeKind::WhileCondition:
  302. case Parse::NodeKind::WhileConditionStart:
  303. return IdKind::InstBlockId;
  304. case Parse::NodeKind::FunctionDefinitionStart:
  305. return IdKind::FunctionId;
  306. case Parse::NodeKind::ClassDefinitionStart:
  307. return IdKind::ClassId;
  308. case Parse::NodeKind::Name:
  309. return IdKind::NameId;
  310. case Parse::NodeKind::AbstractModifier:
  311. case Parse::NodeKind::ArrayExprSemi:
  312. case Parse::NodeKind::BaseModifier:
  313. case Parse::NodeKind::ClassIntroducer:
  314. case Parse::NodeKind::CodeBlockStart:
  315. case Parse::NodeKind::FunctionIntroducer:
  316. case Parse::NodeKind::IfStatementElse:
  317. case Parse::NodeKind::ImplicitParamListStart:
  318. case Parse::NodeKind::LetIntroducer:
  319. case Parse::NodeKind::ParamListStart:
  320. case Parse::NodeKind::ParenExprOrTupleLiteralStart:
  321. case Parse::NodeKind::QualifiedDecl:
  322. case Parse::NodeKind::ReturnedModifier:
  323. case Parse::NodeKind::ReturnStatementStart:
  324. case Parse::NodeKind::ReturnVarModifier:
  325. case Parse::NodeKind::SelfValueName:
  326. case Parse::NodeKind::StructLiteralOrStructTypeLiteralStart:
  327. case Parse::NodeKind::VariableInitializer:
  328. case Parse::NodeKind::VariableIntroducer:
  329. return IdKind::SoloParseNode;
  330. default:
  331. return IdKind::Unused;
  332. }
  333. }
  334. // Translates an ID type to the enum ID kind for comparison with
  335. // ParseNodeKindToIdKind.
  336. template <typename IdT>
  337. static constexpr auto IdTypeToIdKind() -> IdKind {
  338. if constexpr (std::is_same_v<IdT, SemIR::InstId>) {
  339. return IdKind::InstId;
  340. }
  341. if constexpr (std::is_same_v<IdT, SemIR::InstBlockId>) {
  342. return IdKind::InstBlockId;
  343. }
  344. if constexpr (std::is_same_v<IdT, SemIR::FunctionId>) {
  345. return IdKind::FunctionId;
  346. }
  347. if constexpr (std::is_same_v<IdT, SemIR::ClassId>) {
  348. return IdKind::ClassId;
  349. }
  350. if constexpr (std::is_same_v<IdT, SemIR::NameId>) {
  351. return IdKind::NameId;
  352. }
  353. if constexpr (std::is_same_v<IdT, SemIR::TypeId>) {
  354. return IdKind::TypeId;
  355. }
  356. }
  357. // Pops an entry.
  358. template <typename IdT>
  359. auto PopEntry() -> Entry {
  360. Entry back = stack_.pop_back_val();
  361. CARBON_VLOG() << "Node Pop " << stack_.size() << ": "
  362. << parse_tree_->node_kind(back.parse_node) << " -> "
  363. << back.id<IdT>() << "\n";
  364. return back;
  365. }
  366. // Pops the top of the stack and returns the parse_node and the ID.
  367. template <typename IdT>
  368. auto PopWithParseNode() -> std::pair<Parse::NodeId, IdT> {
  369. Entry back = PopEntry<IdT>();
  370. RequireIdKind(parse_tree_->node_kind(back.parse_node),
  371. IdTypeToIdKind<IdT>());
  372. return {back.parse_node, back.id<IdT>()};
  373. }
  374. // Require a Parse::NodeKind be mapped to a particular IdKind.
  375. auto RequireIdKind(Parse::NodeKind parse_kind, IdKind id_kind) const -> void {
  376. CARBON_CHECK(ParseNodeKindToIdKind(parse_kind) == id_kind)
  377. << "Unexpected IdKind mapping for " << parse_kind;
  378. }
  379. // Require an entry to have the given Parse::NodeKind.
  380. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  381. auto RequireParseKind(Parse::NodeId parse_node) const -> void {
  382. auto actual_kind = parse_tree_->node_kind(parse_node);
  383. CARBON_CHECK(RequiredParseKind == actual_kind)
  384. << "Expected " << Parse::NodeKind::Create(RequiredParseKind)
  385. << ", found " << actual_kind;
  386. }
  387. // The file's parse tree.
  388. const Parse::Tree* parse_tree_;
  389. // Whether to print verbose output.
  390. llvm::raw_ostream* vlog_stream_;
  391. // The actual stack.
  392. // PushEntry and PopEntry control modification in order to centralize
  393. // vlogging.
  394. llvm::SmallVector<Entry> stack_;
  395. };
  396. } // namespace Carbon::Check
  397. #endif // CARBON_TOOLCHAIN_CHECK_NODE_STACK_H_