token_index.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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_LEX_TOKEN_INDEX_H_
  5. #define CARBON_TOOLCHAIN_LEX_TOKEN_INDEX_H_
  6. #include "toolchain/base/index_base.h"
  7. #include "toolchain/lex/token_kind.h"
  8. namespace Carbon::Lex {
  9. // A lightweight handle to a lexed token in a `TokenizedBuffer`.
  10. //
  11. // `TokenIndex` objects are designed to be passed by value, not reference or
  12. // pointer. They are also designed to be small and efficient to store in data
  13. // structures.
  14. //
  15. // `TokenIndex` objects from the same `TokenizedBuffer` can be compared with
  16. // each other, both for being the same token within the buffer, and to establish
  17. // relative position within the token stream that has been lexed out of the
  18. // buffer. `TokenIndex` objects from different `TokenizedBuffer`s cannot be
  19. // meaningfully compared.
  20. //
  21. // All other APIs to query a `TokenIndex` are on the `TokenizedBuffer`.
  22. struct TokenIndex : public IndexBase<TokenIndex> {
  23. // The number of bits which must be allotted for `TokenIndex`.
  24. static constexpr int Bits = 23;
  25. // The maximum number of tokens that can be stored, including the FileStart
  26. // and FileEnd tokens.
  27. static constexpr int Max = 1 << Bits;
  28. static constexpr llvm::StringLiteral Label = "token";
  29. static const TokenIndex None;
  30. // Comments aren't tokenized, so this is the first token after FileStart.
  31. static const TokenIndex FirstNonCommentToken;
  32. using IndexBase::IndexBase;
  33. };
  34. constexpr TokenIndex TokenIndex::None(TokenIndex::NoneIndex);
  35. constexpr TokenIndex TokenIndex::FirstNonCommentToken(1);
  36. // A lightweight handle to a lexed token in a `TokenizedBuffer` whose kind is
  37. // known to be `Kind`.
  38. template <const TokenKind& K>
  39. struct TokenIndexForKind : public TokenIndex {
  40. // NOLINTNEXTLINE(readability-identifier-naming)
  41. static const TokenKind& Kind;
  42. constexpr explicit TokenIndexForKind(TokenIndex index) : TokenIndex(index) {}
  43. };
  44. template <const TokenKind& K>
  45. const TokenKind& TokenIndexForKind<K>::Kind = K;
  46. #define CARBON_TOKEN(TokenName) \
  47. using TokenName##TokenIndex = TokenIndexForKind<TokenKind::TokenName>;
  48. #include "toolchain/lex/token_kind.def"
  49. } // namespace Carbon::Lex
  50. #endif // CARBON_TOOLCHAIN_LEX_TOKEN_INDEX_H_