tokenized_buffer.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 TOOLCHAIN_LEXER_TOKENIZED_BUFFER_H_
  5. #define TOOLCHAIN_LEXER_TOKENIZED_BUFFER_H_
  6. #include <cstdint>
  7. #include <iterator>
  8. #include "common/ostream.h"
  9. #include "llvm/ADT/APInt.h"
  10. #include "llvm/ADT/DenseMap.h"
  11. #include "llvm/ADT/Optional.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/iterator.h"
  15. #include "llvm/ADT/iterator_range.h"
  16. #include "llvm/Support/raw_ostream.h"
  17. #include "toolchain/diagnostics/diagnostic_emitter.h"
  18. #include "toolchain/lexer/token_kind.h"
  19. #include "toolchain/source/source_buffer.h"
  20. namespace Carbon {
  21. class TokenizedBuffer;
  22. namespace Internal {
  23. // A lightweight handle to a lexed token in a `TokenizedBuffer`.
  24. //
  25. // This type's preferred name is `TokenizedBuffer::Token` and is only defined
  26. // outside the class to break a dependency cycle.
  27. //
  28. // `Token` objects are designed to be passed by value, not reference or
  29. // pointer. They are also designed to be small and efficient to store in data
  30. // structures.
  31. //
  32. // `Token` objects from the same `TokenizedBuffer` can be compared with each
  33. // other, both for being the same token within the buffer, and to establish
  34. // relative position within the token stream that has been lexed out of the
  35. // buffer. `Token` objects from different `TokenizedBuffer`s cannot be
  36. // meaningfully compared.
  37. //
  38. // All other APIs to query a `Token` are on the `TokenizedBuffer`.
  39. class TokenizedBufferToken {
  40. public:
  41. using Token = TokenizedBufferToken;
  42. TokenizedBufferToken() = default;
  43. friend auto operator==(Token lhs, Token rhs) -> bool {
  44. return lhs.index == rhs.index;
  45. }
  46. friend auto operator!=(Token lhs, Token rhs) -> bool {
  47. return lhs.index != rhs.index;
  48. }
  49. friend auto operator<(Token lhs, Token rhs) -> bool {
  50. return lhs.index < rhs.index;
  51. }
  52. friend auto operator<=(Token lhs, Token rhs) -> bool {
  53. return lhs.index <= rhs.index;
  54. }
  55. friend auto operator>(Token lhs, Token rhs) -> bool {
  56. return lhs.index > rhs.index;
  57. }
  58. friend auto operator>=(Token lhs, Token rhs) -> bool {
  59. return lhs.index >= rhs.index;
  60. }
  61. private:
  62. friend TokenizedBuffer;
  63. explicit TokenizedBufferToken(int index) : index(index) {}
  64. int32_t index;
  65. };
  66. } // namespace Internal
  67. // A buffer of tokenized Carbon source code.
  68. //
  69. // This is constructed by lexing the source code text into a series of tokens.
  70. // The buffer provides lightweight handles to tokens and other lexed entities,
  71. // as well as iterations to walk the sequence of tokens found in the buffer.
  72. //
  73. // Lexing errors result in a potentially incomplete sequence of tokens and
  74. // `HasError` returning true.
  75. class TokenizedBuffer {
  76. public:
  77. // A lightweight handle to a lexed token in a `TokenizedBuffer`.
  78. using Token = Internal::TokenizedBufferToken;
  79. // A lightweight handle to a lexed line in a `TokenizedBuffer`.
  80. //
  81. // `Line` objects are designed to be passed by value, not reference or
  82. // pointer. They are also designed to be small and efficient to store in data
  83. // structures.
  84. //
  85. // Each `Line` object refers to a specific line in the source code that was
  86. // lexed. They can be compared directly to establish that they refer to the
  87. // same line or the relative position of different lines within the source.
  88. //
  89. // All other APIs to query a `Line` are on the `TokenizedBuffer`.
  90. class Line {
  91. public:
  92. Line() = default;
  93. friend auto operator==(Line lhs, Line rhs) -> bool {
  94. return lhs.index == rhs.index;
  95. }
  96. friend auto operator!=(Line lhs, Line rhs) -> bool {
  97. return lhs.index != rhs.index;
  98. }
  99. friend auto operator<(Line lhs, Line rhs) -> bool {
  100. return lhs.index < rhs.index;
  101. }
  102. friend auto operator<=(Line lhs, Line rhs) -> bool {
  103. return lhs.index <= rhs.index;
  104. }
  105. friend auto operator>(Line lhs, Line rhs) -> bool {
  106. return lhs.index > rhs.index;
  107. }
  108. friend auto operator>=(Line lhs, Line rhs) -> bool {
  109. return lhs.index >= rhs.index;
  110. }
  111. private:
  112. friend class TokenizedBuffer;
  113. explicit Line(int index) : index(index) {}
  114. int32_t index;
  115. };
  116. // A lightweight handle to a lexed identifier in a `TokenizedBuffer`.
  117. //
  118. // `Identifier` objects are designed to be passed by value, not reference or
  119. // pointer. They are also designed to be small and efficient to store in data
  120. // structures.
  121. //
  122. // Each identifier lexed is canonicalized to a single entry in the identifier
  123. // table. `Identifier` objects will compare equal if they refer to the same
  124. // identifier spelling. Where the identifier was written is not preserved.
  125. //
  126. // All other APIs to query a `Identifier` are on the `TokenizedBuffer`.
  127. class Identifier {
  128. public:
  129. Identifier() = default;
  130. // Most normal APIs are provided by the `TokenizedBuffer`, we just support
  131. // basic comparison operations.
  132. friend auto operator==(Identifier lhs, Identifier rhs) -> bool {
  133. return lhs.index == rhs.index;
  134. }
  135. friend auto operator!=(Identifier lhs, Identifier rhs) -> bool {
  136. return lhs.index != rhs.index;
  137. }
  138. private:
  139. friend class TokenizedBuffer;
  140. explicit Identifier(int index) : index(index) {}
  141. int32_t index;
  142. };
  143. // Random-access iterator over tokens within the buffer.
  144. class TokenIterator
  145. : public llvm::iterator_facade_base<
  146. TokenIterator, std::random_access_iterator_tag, const Token, int> {
  147. public:
  148. TokenIterator() = default;
  149. explicit TokenIterator(Token token) : token(token) {}
  150. auto operator==(const TokenIterator& rhs) const -> bool {
  151. return token == rhs.token;
  152. }
  153. auto operator<(const TokenIterator& rhs) const -> bool {
  154. return token < rhs.token;
  155. }
  156. auto operator*() const -> const Token& { return token; }
  157. using iterator_facade_base::operator-;
  158. auto operator-(const TokenIterator& rhs) const -> int {
  159. return token.index - rhs.token.index;
  160. }
  161. auto operator+=(int n) -> TokenIterator& {
  162. token.index += n;
  163. return *this;
  164. }
  165. auto operator-=(int n) -> TokenIterator& {
  166. token.index -= n;
  167. return *this;
  168. }
  169. // Prints the raw token index.
  170. auto Print(llvm::raw_ostream& output) const -> void;
  171. private:
  172. friend class TokenizedBuffer;
  173. Token token;
  174. };
  175. // The value of a real literal.
  176. //
  177. // This is either a dyadic fraction (mantissa * 2^exponent) or a decadic
  178. // fraction (mantissa * 10^exponent).
  179. //
  180. // The `TokenizedBuffer` must outlive any `RealLiteralValue`s referring to
  181. // its tokens.
  182. class RealLiteralValue {
  183. const TokenizedBuffer* buffer;
  184. int32_t literal_index;
  185. bool is_decimal;
  186. public:
  187. // The mantissa, represented as an unsigned integer.
  188. [[nodiscard]] auto Mantissa() const -> const llvm::APInt& {
  189. return buffer->literal_int_storage[literal_index];
  190. }
  191. // The exponent, represented as a signed integer.
  192. [[nodiscard]] auto Exponent() const -> const llvm::APInt& {
  193. return buffer->literal_int_storage[literal_index + 1];
  194. }
  195. // If false, the value is mantissa * 2^exponent.
  196. // If true, the value is mantissa * 10^exponent.
  197. [[nodiscard]] auto IsDecimal() const -> bool { return is_decimal; }
  198. private:
  199. friend class TokenizedBuffer;
  200. RealLiteralValue(const TokenizedBuffer* buffer, int32_t literal_index,
  201. bool is_decimal)
  202. : buffer(buffer),
  203. literal_index(literal_index),
  204. is_decimal(is_decimal) {}
  205. };
  206. // A diagnostic location translator that maps token locations into source
  207. // buffer locations.
  208. class TokenLocationTranslator
  209. : public DiagnosticLocationTranslator<Internal::TokenizedBufferToken> {
  210. public:
  211. explicit TokenLocationTranslator(TokenizedBuffer& buffer)
  212. : buffer_(&buffer) {}
  213. // Map the given token into a diagnostic location.
  214. auto GetLocation(Token token) -> Diagnostic::Location override;
  215. private:
  216. TokenizedBuffer* buffer_;
  217. };
  218. // Lexes a buffer of source code into a tokenized buffer.
  219. //
  220. // The provided source buffer must outlive any returned `TokenizedBuffer`
  221. // which will refer into the source.
  222. static auto Lex(SourceBuffer& source, DiagnosticConsumer& consumer)
  223. -> TokenizedBuffer;
  224. // Returns true if the buffer has errors that are detectable at lexing time.
  225. [[nodiscard]] auto HasErrors() const -> bool { return has_errors; }
  226. [[nodiscard]] auto Tokens() const -> llvm::iterator_range<TokenIterator> {
  227. return llvm::make_range(TokenIterator(Token(0)),
  228. TokenIterator(Token(token_infos.size())));
  229. }
  230. [[nodiscard]] auto Size() const -> int { return token_infos.size(); }
  231. [[nodiscard]] auto GetKind(Token token) const -> TokenKind;
  232. [[nodiscard]] auto GetLine(Token token) const -> Line;
  233. // Returns the 1-based line number.
  234. [[nodiscard]] auto GetLineNumber(Token token) const -> int;
  235. // Returns the 1-based column number.
  236. [[nodiscard]] auto GetColumnNumber(Token token) const -> int;
  237. // Returns the source text lexed into this token.
  238. [[nodiscard]] auto GetTokenText(Token token) const -> llvm::StringRef;
  239. // Returns the identifier associated with this token. The token kind must be
  240. // an `Identifier`.
  241. [[nodiscard]] auto GetIdentifier(Token token) const -> Identifier;
  242. // Returns the value of an `IntegerLiteral()` token.
  243. [[nodiscard]] auto GetIntegerLiteral(Token token) const -> const llvm::APInt&;
  244. // Returns the value of an `RealLiteral()` token.
  245. [[nodiscard]] auto GetRealLiteral(Token token) const -> RealLiteralValue;
  246. // Returns the value of a `StringLiteral()` token.
  247. [[nodiscard]] auto GetStringLiteral(Token token) const -> llvm::StringRef;
  248. // Returns the size specified in a `*TypeLiteral()` token.
  249. [[nodiscard]] auto GetTypeLiteralSize(Token token) const
  250. -> const llvm::APInt&;
  251. // Returns the closing token matched with the given opening token.
  252. //
  253. // The given token must be an opening token kind.
  254. [[nodiscard]] auto GetMatchedClosingToken(Token opening_token) const -> Token;
  255. // Returns the opening token matched with the given closing token.
  256. //
  257. // The given token must be a closing token kind.
  258. [[nodiscard]] auto GetMatchedOpeningToken(Token closing_token) const -> Token;
  259. // Returns whether the given token has leading whitespace.
  260. [[nodiscard]] auto HasLeadingWhitespace(Token token) const -> bool;
  261. // Returns whether the given token has trailing whitespace.
  262. [[nodiscard]] auto HasTrailingWhitespace(Token token) const -> bool;
  263. // Returns whether the token was created as part of an error recovery effort.
  264. //
  265. // For example, a closing paren inserted to match an unmatched paren.
  266. [[nodiscard]] auto IsRecoveryToken(Token token) const -> bool;
  267. // Returns the 1-based line number.
  268. [[nodiscard]] auto GetLineNumber(Line line) const -> int;
  269. // Returns the 1-based indentation column number.
  270. [[nodiscard]] auto GetIndentColumnNumber(Line line) const -> int;
  271. // Returns the text for an identifier.
  272. [[nodiscard]] auto GetIdentifierText(Identifier id) const -> llvm::StringRef;
  273. // Prints a description of the tokenized stream to the provided `raw_ostream`.
  274. //
  275. // It prints one line of information for each token in the buffer, including
  276. // the kind of token, where it occurs within the source file, indentation for
  277. // the associated line, the spelling of the token in source, and any
  278. // additional information tracked such as which unique identifier it is or any
  279. // matched grouping token.
  280. //
  281. // Each line is formatted as a YAML record:
  282. //
  283. // clang-format off
  284. // ```
  285. // token: { index: 0, kind: 'Semi', line: 1, column: 1, indent: 1, spelling: ';' }
  286. // ```
  287. // clang-format on
  288. //
  289. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  290. // on the command line. The format is also reasonably amenable to other
  291. // line-oriented shell tools from `grep` to `awk`.
  292. auto Print(llvm::raw_ostream& output_stream) const -> void;
  293. // Prints a description of a single token. See `print` for details on the
  294. // format.
  295. auto PrintToken(llvm::raw_ostream& output_stream, Token token) const -> void;
  296. private:
  297. // Implementation detail struct implementing the actual lexer logic.
  298. class Lexer;
  299. friend Lexer;
  300. // A diagnostic location translator that maps token locations into source
  301. // buffer locations.
  302. class SourceBufferLocationTranslator
  303. : public DiagnosticLocationTranslator<const char*> {
  304. public:
  305. explicit SourceBufferLocationTranslator(TokenizedBuffer& buffer)
  306. : buffer_(&buffer) {}
  307. // Map the given position within the source buffer into a diagnostic
  308. // location.
  309. auto GetLocation(const char* pos) -> Diagnostic::Location override;
  310. private:
  311. TokenizedBuffer* buffer_;
  312. };
  313. // Specifies minimum widths to use when printing a token's fields via
  314. // `printToken`.
  315. struct PrintWidths {
  316. // Widens `this` to the maximum of `this` and `new_width` for each
  317. // dimension.
  318. auto Widen(const PrintWidths& new_width) -> void;
  319. int index;
  320. int kind;
  321. int column;
  322. int line;
  323. int indent;
  324. };
  325. struct TokenInfo {
  326. TokenKind kind;
  327. // Whether the token has trailing whitespace.
  328. bool has_trailing_space = false;
  329. // Whether the token was injected artificially during error recovery.
  330. bool is_recovery = false;
  331. // Line on which the Token starts.
  332. Line token_line;
  333. // Zero-based byte offset of the token within its line.
  334. int32_t column;
  335. // We may have up to 32 bits of payload, based on the kind of token.
  336. union {
  337. static_assert(
  338. sizeof(Token) <= sizeof(int32_t),
  339. "Unable to pack token and identifier index into the same space!");
  340. Identifier id;
  341. int32_t literal_index;
  342. Token closing_token;
  343. Token opening_token;
  344. int32_t error_length;
  345. };
  346. };
  347. struct LineInfo {
  348. // Zero-based byte offset of the start of the line within the source buffer
  349. // provided.
  350. int64_t start;
  351. // The byte length of the line. Does not include the newline character (or a
  352. // null terminator or EOF).
  353. int32_t length;
  354. // The byte offset from the start of the line of the first non-whitespace
  355. // character.
  356. int32_t indent;
  357. };
  358. struct IdentifierInfo {
  359. llvm::StringRef text;
  360. };
  361. // The constructor is merely responsible for trivial initialization of
  362. // members. A working object of this type is built with the `lex` function
  363. // above so that its return can indicate if an error was encountered while
  364. // lexing.
  365. explicit TokenizedBuffer(SourceBuffer& source) : source(&source) {}
  366. auto GetLineInfo(Line line) -> LineInfo&;
  367. [[nodiscard]] auto GetLineInfo(Line line) const -> const LineInfo&;
  368. auto AddLine(LineInfo info) -> Line;
  369. auto GetTokenInfo(Token token) -> TokenInfo&;
  370. [[nodiscard]] auto GetTokenInfo(Token token) const -> const TokenInfo&;
  371. auto AddToken(TokenInfo info) -> Token;
  372. [[nodiscard]] auto GetTokenPrintWidths(Token token) const -> PrintWidths;
  373. auto PrintToken(llvm::raw_ostream& output_stream, Token token,
  374. PrintWidths widths) const -> void;
  375. SourceBuffer* source;
  376. llvm::SmallVector<TokenInfo, 16> token_infos;
  377. llvm::SmallVector<LineInfo, 16> line_infos;
  378. llvm::SmallVector<IdentifierInfo, 16> identifier_infos;
  379. // Storage for integers that form part of the value of a numeric or type
  380. // literal.
  381. llvm::SmallVector<llvm::APInt, 16> literal_int_storage;
  382. llvm::SmallVector<std::string, 16> literal_string_storage;
  383. llvm::DenseMap<llvm::StringRef, Identifier> identifier_map;
  384. bool has_errors = false;
  385. };
  386. // A diagnostic emitter that uses positions within a source buffer's text as
  387. // its source of location information.
  388. using LexerDiagnosticEmitter = DiagnosticEmitter<const char*>;
  389. // A diagnostic emitter that uses tokens as its source of location information.
  390. using TokenDiagnosticEmitter = DiagnosticEmitter<TokenizedBuffer::Token>;
  391. } // namespace Carbon
  392. #endif // TOOLCHAIN_LEXER_TOKENIZED_BUFFER_H_