token_index.h 2.4 KB

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