node_stack.h 19 KB

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