semantics_node_block_stack.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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_SEMANTICS_SEMANTICS_NODE_BLOCK_STACK_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_BLOCK_STACK_H_
  6. #include <type_traits>
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "toolchain/semantics/semantics_node.h"
  9. namespace Carbon {
  10. // Wraps the stack of node blocks for SemanticsParseTreeHandler.
  11. //
  12. // All pushes and pops will be vlogged.
  13. class SemanticsNodeBlockStack {
  14. public:
  15. explicit SemanticsNodeBlockStack(
  16. llvm::StringLiteral name,
  17. llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>>& node_blocks,
  18. llvm::raw_ostream* vlog_stream)
  19. : name_(name), node_blocks_(&node_blocks), vlog_stream_(vlog_stream) {}
  20. // Pushes a new node block. It will be invalid unless PeekForAdd is called in
  21. // order to support lazy allocation.
  22. auto Push() -> void;
  23. // Allocates and pushes a new node block.
  24. auto PushForAdd() -> SemanticsNodeBlockId {
  25. Push();
  26. return PeekForAdd();
  27. }
  28. // Peeks at the top node block. This does not trigger lazy allocation, so the
  29. // returned node block may be invalid.
  30. auto Peek() -> SemanticsNodeBlockId { return stack_.back(); }
  31. // Returns the top node block, allocating one if it's still invalid.
  32. auto PeekForAdd() -> SemanticsNodeBlockId;
  33. // Pops the top node block. This will always return a valid node block;
  34. // SemanticsNodeBlockId::Empty is returned if one wasn't allocated.
  35. auto Pop() -> SemanticsNodeBlockId;
  36. // Prints the stack for a stack dump.
  37. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  38. auto empty() const -> bool { return stack_.empty(); }
  39. auto size() const -> size_t { return stack_.size(); }
  40. private:
  41. // A name for debugging.
  42. llvm::StringLiteral name_;
  43. // The underlying node block storage on SemanticsIR. Always non-null.
  44. llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>>* const node_blocks_;
  45. // Whether to print verbose output.
  46. llvm::raw_ostream* vlog_stream_;
  47. // The actual stack.
  48. // PushEntry and PopEntry control modification in order to centralize
  49. // vlogging.
  50. llvm::SmallVector<SemanticsNodeBlockId> stack_;
  51. };
  52. } // namespace Carbon
  53. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_BLOCK_STACK_H_