node_stack.h 18 KB

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