parse_node_kind.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 PARSER_PARSE_NODE_KIND_H_
  5. #define PARSER_PARSE_NODE_KIND_H_
  6. #include <cstdint>
  7. #include <iterator>
  8. #include "llvm/ADT/StringRef.h"
  9. namespace Carbon {
  10. // A class wrapping an enumeration of the different kinds of nodes in the parse
  11. // tree.
  12. //
  13. // Rather than using a raw enumerator for each distinct kind of node produced by
  14. // the parser, we wrap the enumerator in a class to expose a more rich API
  15. // including bidirectional mappings to string spellings of the different kinds
  16. // and any relevant classification.
  17. //
  18. // Instances of this type should always be created using the `constexpr` static
  19. // member functions. These instances are designed specifically to be usable in
  20. // `case` labels of `switch` statements just like an enumerator would.
  21. class ParseNodeKind {
  22. public:
  23. // The formatting for this macro is weird due to a `clang-format` bug. See
  24. // https://bugs.llvm.org/show_bug.cgi?id=48320 for details.
  25. #define CARBON_PARSE_NODE_KIND(Name) \
  26. static constexpr auto Name()->ParseNodeKind { return KindEnum::Name; }
  27. #include "parser/parse_node_kind.def"
  28. // The default constructor is deleted as objects of this type should always be
  29. // constructed using the above factory functions for each unique kind.
  30. ParseNodeKind() = delete;
  31. auto operator==(const ParseNodeKind& rhs) const -> bool {
  32. return kind == rhs.kind;
  33. }
  34. auto operator!=(const ParseNodeKind& rhs) const -> bool {
  35. return kind != rhs.kind;
  36. }
  37. // Gets a friendly name for the token for logging or debugging.
  38. [[nodiscard]] auto GetName() const -> llvm::StringRef;
  39. private:
  40. enum class KindEnum : uint8_t {
  41. #define CARBON_PARSE_NODE_KIND(Name) Name,
  42. #include "parser/parse_node_kind.def"
  43. };
  44. constexpr ParseNodeKind(KindEnum k) : kind(k) {}
  45. // Enable conversion to our private enum, including in a `constexpr` context,
  46. // to enable usage in `switch` and `case`. The enum remains private and
  47. // nothing else should be using this.
  48. explicit constexpr operator KindEnum() const { return kind; }
  49. KindEnum kind;
  50. };
  51. // We expect the parse node kind to fit compactly into 8 bits.
  52. static_assert(sizeof(ParseNodeKind) == 1, "Kind objects include padding!");
  53. } // namespace Carbon
  54. #endif // PARSER_PARSE_NODE_KIND_H_