token_index.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 {
  23. static const TokenIndex Invalid;
  24. // Comments aren't tokenized, so this is the first token after FileStart.
  25. static const TokenIndex FirstNonCommentToken;
  26. using IndexBase::IndexBase;
  27. };
  28. constexpr TokenIndex TokenIndex::Invalid(TokenIndex::InvalidIndex);
  29. constexpr TokenIndex TokenIndex::FirstNonCommentToken(1);
  30. // A lightweight handle to a lexed token in a `TokenizedBuffer` whose kind is
  31. // known to be `Kind`.
  32. template <const TokenKind& K>
  33. struct TokenIndexForKind : public TokenIndex {
  34. // NOLINTNEXTLINE(readability-identifier-naming)
  35. static const TokenKind& Kind;
  36. constexpr explicit TokenIndexForKind(TokenIndex index) : TokenIndex(index) {}
  37. };
  38. template <const TokenKind& K>
  39. const TokenKind& TokenIndexForKind<K>::Kind = K;
  40. #define CARBON_TOKEN(TokenName) \
  41. using TokenName##TokenIndex = TokenIndexForKind<TokenKind::TokenName>;
  42. #include "toolchain/lex/token_kind.def"
  43. } // namespace Carbon::Lex
  44. #endif // CARBON_TOOLCHAIN_LEX_TOKEN_INDEX_H_