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/node.h"
  12. namespace Carbon::Check {
  13. // Wraps the stack of nodes for Context.
  14. //
  15. // All pushes and pops will be vlogged.
  16. //
  17. // Pop APIs will run basic verification:
  18. //
  19. // - If receiving a pop_parse_kind, verify that the parse_node being popped is
  20. // of pop_parse_kind.
  21. // - Validates presence of node_id based on whether it's a solo
  22. // parse_node.
  23. //
  24. // These should be assumed API constraints unless otherwise mentioned on a
  25. // method. The main exception is PopAndIgnore, which doesn't do verification.
  26. class NodeStack {
  27. public:
  28. explicit NodeStack(const Parse::Tree& parse_tree,
  29. llvm::raw_ostream* vlog_stream)
  30. : parse_tree_(&parse_tree), vlog_stream_(vlog_stream) {}
  31. // Pushes a solo parse tree node onto the stack. Used when there is no
  32. // IR generated by the node.
  33. auto Push(Parse::Node parse_node) -> void {
  34. CARBON_CHECK(ParseNodeKindToIdKind(parse_tree_->node_kind(parse_node)) ==
  35. IdKind::SoloParseNode)
  36. << "Parse kind expects an Id: " << parse_tree_->node_kind(parse_node);
  37. CARBON_VLOG() << "Node Push " << stack_.size() << ": "
  38. << parse_tree_->node_kind(parse_node) << " -> <none>\n";
  39. CARBON_CHECK(stack_.size() < (1 << 20))
  40. << "Excessive stack size: likely infinite loop";
  41. stack_.push_back(Entry(parse_node, SemIR::NodeId::Invalid));
  42. }
  43. // Pushes a parse tree node onto the stack with an ID.
  44. template <typename IdT>
  45. auto Push(Parse::Node parse_node, IdT id) -> void {
  46. CARBON_CHECK(ParseNodeKindToIdKind(parse_tree_->node_kind(parse_node)) ==
  47. IdTypeToIdKind<IdT>())
  48. << "Parse kind expected a different IdT: "
  49. << parse_tree_->node_kind(parse_node) << " -> " << id << "\n";
  50. CARBON_CHECK(id.is_valid()) << "Push called with invalid id: "
  51. << parse_tree_->node_kind(parse_node);
  52. CARBON_VLOG() << "Node Push " << stack_.size() << ": "
  53. << parse_tree_->node_kind(parse_node) << " -> " << id << "\n";
  54. CARBON_CHECK(stack_.size() < (1 << 20))
  55. << "Excessive stack size: likely infinite loop";
  56. stack_.push_back(Entry(parse_node, id));
  57. }
  58. // Returns whether the node on the top of the stack is the specified kind.
  59. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  60. auto PeekIs() const -> bool {
  61. return parse_tree_->node_kind(PeekParseNode()) == RequiredParseKind;
  62. }
  63. // Pops the top of the stack without any verification.
  64. auto PopAndIgnore() -> void { PopEntry<SemIR::NodeId>(); }
  65. // Pops the top of the stack and returns the parse_node.
  66. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  67. auto PopForSoloParseNode() -> Parse::Node {
  68. Entry back = PopEntry<SemIR::NodeId>();
  69. RequireIdKind(Parse::NodeKind::Create(RequiredParseKind),
  70. IdKind::SoloParseNode);
  71. RequireParseKind<RequiredParseKind>(back.parse_node);
  72. return back.parse_node;
  73. }
  74. // Pops the top of the stack if it is the given kind, and returns the
  75. // parse_node. Otherwise, returns std::nullopt.
  76. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  77. auto PopForSoloParseNodeIf() -> std::optional<Parse::Node> {
  78. if (PeekIs<RequiredParseKind>()) {
  79. return PopForSoloParseNode<RequiredParseKind>();
  80. }
  81. return std::nullopt;
  82. }
  83. // Pops the top of the stack.
  84. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  85. auto PopAndDiscardSoloParseNode() -> void {
  86. PopForSoloParseNode<RequiredParseKind>();
  87. }
  88. // Pops an expression from the top of the stack and returns the parse_node and
  89. // the ID.
  90. auto PopExpressionWithParseNode() -> std::pair<Parse::Node, SemIR::NodeId> {
  91. return PopWithParseNode<SemIR::NodeId>();
  92. }
  93. // Pops the top of the stack and returns the parse_node and the ID.
  94. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  95. auto PopWithParseNode() -> auto {
  96. constexpr IdKind RequiredIdKind =
  97. ParseNodeKindToIdKind(Parse::NodeKind::Create(RequiredParseKind));
  98. if constexpr (RequiredIdKind == IdKind::NodeId) {
  99. auto back = PopWithParseNode<SemIR::NodeId>();
  100. RequireParseKind<RequiredParseKind>(back.first);
  101. return back;
  102. }
  103. if constexpr (RequiredIdKind == IdKind::NodeBlockId) {
  104. auto back = PopWithParseNode<SemIR::NodeBlockId>();
  105. RequireParseKind<RequiredParseKind>(back.first);
  106. return back;
  107. }
  108. if constexpr (RequiredIdKind == IdKind::FunctionId) {
  109. auto back = PopWithParseNode<SemIR::FunctionId>();
  110. RequireParseKind<RequiredParseKind>(back.first);
  111. return back;
  112. }
  113. if constexpr (RequiredIdKind == IdKind::ClassId) {
  114. auto back = PopWithParseNode<SemIR::ClassId>();
  115. RequireParseKind<RequiredParseKind>(back.first);
  116. return back;
  117. }
  118. if constexpr (RequiredIdKind == IdKind::StringId) {
  119. auto back = PopWithParseNode<StringId>();
  120. RequireParseKind<RequiredParseKind>(back.first);
  121. return back;
  122. }
  123. if constexpr (RequiredIdKind == IdKind::TypeId) {
  124. auto back = PopWithParseNode<SemIR::TypeId>();
  125. RequireParseKind<RequiredParseKind>(back.first);
  126. return back;
  127. }
  128. CARBON_FATAL() << "Unpoppable IdKind for parse kind: "
  129. << Parse::NodeKind::Create(RequiredParseKind)
  130. << "; see value in ParseNodeKindToIdKind";
  131. }
  132. // Pops an expression from the top of the stack and returns the ID.
  133. // Expressions map multiple Parse::NodeKinds to SemIR::NodeId always.
  134. auto PopExpression() -> SemIR::NodeId {
  135. return PopExpressionWithParseNode().second;
  136. }
  137. // Pops the top of the stack and returns the ID.
  138. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  139. auto Pop() -> auto {
  140. return PopWithParseNode<RequiredParseKind>().second;
  141. }
  142. // Pops the top of the stack if it has the given kind, and returns the ID.
  143. // Otherwise returns std::nullopt.
  144. template <Parse::NodeKind::RawEnumType RequiredParseKind>
  145. auto PopIf() -> std::optional<decltype(Pop<RequiredParseKind>())> {
  146. if (PeekIs<RequiredParseKind>()) {
  147. return Pop<RequiredParseKind>();
  148. }
  149. return std::nullopt;
  150. }
  151. // Peeks at the parse_node of the given depth in the stack, or by default the
  152. // top node.
  153. auto PeekParseNode() const -> Parse::Node { return stack_.back().parse_node; }
  154. // Peeks at the ID of node at the given depth in the stack, or by default the
  155. // top node.
  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::NodeId) {
  163. return back.id<SemIR::NodeId>();
  164. }
  165. if constexpr (RequiredIdKind == IdKind::NodeBlockId) {
  166. return back.id<SemIR::NodeBlockId>();
  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::StringId) {
  175. return back.id<StringId>();
  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. NodeId,
  192. NodeBlockId,
  193. FunctionId,
  194. ClassId,
  195. StringId,
  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::NodeId node_id)
  205. : parse_node(parse_node), node_id(node_id) {}
  206. explicit Entry(Parse::Node parse_node, SemIR::NodeBlockId node_block_id)
  207. : parse_node(parse_node), node_block_id(node_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, StringId 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::NodeId>()) {
  220. return node_id;
  221. }
  222. if constexpr (std::is_same<T, SemIR::NodeBlockId>()) {
  223. return node_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, StringId>()) {
  232. return name_id;
  233. }
  234. if constexpr (std::is_same<T, SemIR::TypeId>()) {
  235. return type_id;
  236. }
  237. }
  238. // The 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::NodeId node_id;
  247. SemIR::NodeBlockId node_block_id;
  248. SemIR::FunctionId function_id;
  249. SemIR::ClassId class_id;
  250. StringId 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::NodeId;
  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::NodeBlockId;
  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::StringId;
  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::NodeId>) {
  320. return IdKind::NodeId;
  321. }
  322. if constexpr (std::is_same_v<IdT, SemIR::NodeBlockId>) {
  323. return IdKind::NodeBlockId;
  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, StringId>) {
  332. return IdKind::StringId;
  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_