parse_subtree_consumer.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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_PARSE_SUBTREE_CONSUMER_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_PARSE_SUBTREE_CONSUMER_H_
  6. #include "toolchain/parser/parse_tree.h"
  7. namespace Carbon {
  8. // Consumes a subtree from the parser, returning only its direct children.
  9. //
  10. // This traverses in reverse postorder because the parent of a subtree needs to
  11. // be seen before its children.
  12. class ParseSubtreeConsumer {
  13. public:
  14. using ParseTreeIterator = std::reverse_iterator<ParseTree::PostorderIterator>;
  15. // Returns a subtree consumer for a particular node in the tree.
  16. static auto ForParent(const ParseTree& parse_tree,
  17. ParseTree::Node parent_node) -> ParseSubtreeConsumer;
  18. // Returns a subtree consumer for the root of the tree.
  19. static auto ForTree(const ParseTree& parse_tree) -> ParseSubtreeConsumer;
  20. // Prevent copies because we require completion of parsing in the destructor.
  21. ParseSubtreeConsumer(const ParseSubtreeConsumer&) = delete;
  22. auto operator=(const ParseSubtreeConsumer&) -> ParseSubtreeConsumer& = delete;
  23. ~ParseSubtreeConsumer();
  24. // Returns the next node.
  25. // CHECK-fails on unexpected states.
  26. [[nodiscard]] auto RequireConsume() -> ParseTree::Node;
  27. // Requires the next node be of the given kind, and returns it.
  28. // CHECK-fails on unexpected states.
  29. [[nodiscard]] auto RequireConsume(ParseNodeKind node_kind) -> ParseTree::Node;
  30. // Returns the next node if one exists.
  31. [[nodiscard]] auto TryConsume() -> llvm::Optional<ParseTree::Node>;
  32. // Returns the next node if it's of the given kind.
  33. [[nodiscard]] auto TryConsume(ParseNodeKind node_kind)
  34. -> llvm::Optional<ParseTree::Node>;
  35. // Returns true if there are no more nodes to consume.
  36. auto is_done() -> bool { return cursor_ == subtree_end_; }
  37. private:
  38. // Constructs for a subtree.
  39. ParseSubtreeConsumer(const ParseTree& parse_tree, ParseTreeIterator cursor,
  40. ParseTreeIterator subtree_end)
  41. : parse_tree_(&parse_tree), cursor_(cursor), subtree_end_(subtree_end) {}
  42. // Advances to the next sibling, returning the current node.
  43. auto GetNodeAndAdvance() -> ParseTree::Node;
  44. const ParseTree* parse_tree_;
  45. ParseTreeIterator cursor_;
  46. ParseTreeIterator subtree_end_;
  47. };
  48. } // namespace Carbon
  49. #endif // CARBON_TOOLCHAIN_SEMANTICS_PARSE_SUBTREE_CONSUMER_H_