parser_state.h 2.2 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_PARSER_PARSER_STATE_H_
  5. #define CARBON_TOOLCHAIN_PARSER_PARSER_STATE_H_
  6. #include <cstdint>
  7. #include <iterator>
  8. #include "common/ostream.h"
  9. #include "llvm/ADT/StringRef.h"
  10. namespace Carbon {
  11. class ParserState {
  12. // Note that this must be declared earlier in the class so that its type can
  13. // be used, for example in the conversion operator.
  14. enum class StateEnum : uint8_t {
  15. #define CARBON_PARSER_STATE(Name) Name,
  16. #include "toolchain/parser/parser_state.def"
  17. };
  18. public:
  19. // `clang-format` has a bug with spacing around `->` returns in macros. See
  20. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  21. #define CARBON_PARSER_STATE(Name) \
  22. static constexpr auto Name()->ParserState { \
  23. return ParserState(StateEnum::Name); \
  24. }
  25. #include "toolchain/parser/parser_state.def"
  26. // The default constructor is deleted because objects of this type should
  27. // always be constructed using the above factory functions for each unique
  28. // kind.
  29. ParserState() = delete;
  30. friend auto operator==(ParserState lhs, ParserState rhs) -> bool {
  31. return lhs.state_ == rhs.state_;
  32. }
  33. friend auto operator!=(ParserState lhs, ParserState rhs) -> bool {
  34. return lhs.state_ != rhs.state_;
  35. }
  36. // Gets a friendly name for the token for logging or debugging.
  37. [[nodiscard]] auto name() const -> llvm::StringRef;
  38. // Enable conversion to our private enum, including in a `constexpr` context,
  39. // to enable usage in `switch` and `case`. The enum remains private and
  40. // nothing else should be using this function.
  41. // NOLINTNEXTLINE(google-explicit-constructor)
  42. constexpr operator StateEnum() const { return state_; }
  43. void Print(llvm::raw_ostream& out) const { out << name(); }
  44. private:
  45. constexpr explicit ParserState(StateEnum k) : state_(k) {}
  46. StateEnum state_;
  47. };
  48. // We expect the parse node kind to fit compactly into 8 bits.
  49. static_assert(sizeof(ParserState) == 1, "ParserState objects include padding!");
  50. } // namespace Carbon
  51. #endif // CARBON_TOOLCHAIN_PARSER_PARSER_STATE_H_