node_stack.h 17 KB

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