tokenized_buffer.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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. #include "toolchain/lex/tokenized_buffer.h"
  5. #include <algorithm>
  6. #include <array>
  7. #include <cmath>
  8. #include "common/check.h"
  9. #include "common/string_helpers.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/ADT/StringSwitch.h"
  12. #include "llvm/Support/ErrorHandling.h"
  13. #include "llvm/Support/Format.h"
  14. #include "llvm/Support/FormatVariadic.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include "toolchain/lex/character_set.h"
  17. #include "toolchain/lex/helpers.h"
  18. #include "toolchain/lex/numeric_literal.h"
  19. #include "toolchain/lex/string_literal.h"
  20. #if __x86_64__
  21. #include <x86intrin.h>
  22. #endif
  23. namespace Carbon::Lex {
  24. // TODO: Move Overload and VariantMatch somewhere more central.
  25. // Form an overload set from a list of functions. For example:
  26. //
  27. // ```
  28. // auto overloaded = Overload{[] (int) {}, [] (float) {}};
  29. // ```
  30. template <typename... Fs>
  31. struct Overload : Fs... {
  32. using Fs::operator()...;
  33. };
  34. template <typename... Fs>
  35. Overload(Fs...) -> Overload<Fs...>;
  36. // Pattern-match against the type of the value stored in the variant `V`. Each
  37. // element of `fs` should be a function that takes one or more of the variant
  38. // values in `V`.
  39. template <typename V, typename... Fs>
  40. auto VariantMatch(V&& v, Fs&&... fs) -> decltype(auto) {
  41. return std::visit(Overload{std::forward<Fs&&>(fs)...}, std::forward<V&&>(v));
  42. }
  43. // Scans the provided text and returns the prefix `StringRef` of contiguous
  44. // identifier characters.
  45. //
  46. // This is a performance sensitive function and so uses vectorized code
  47. // sequences to optimize its scanning. When modifying, the identifier lexing
  48. // benchmarks should be checked for regressions.
  49. //
  50. // Identifier characters here are currently the ASCII characters `[0-9A-Za-z_]`.
  51. //
  52. // TODO: Currently, this code does not implement Carbon's design for Unicode
  53. // characters in identifiers. It does work on UTF-8 code unit sequences, but
  54. // currently considers non-ASCII characters to be non-identifier characters.
  55. // Some work has been done to ensure the hot loop, while optimized, retains
  56. // enough information to add Unicode handling without completely destroying the
  57. // relevant optimizations.
  58. static auto ScanForIdentifierPrefix(llvm::StringRef text) -> llvm::StringRef {
  59. // A table of booleans that we can use to classify bytes as being valid
  60. // identifier (or keyword) characters. This is used in the generic,
  61. // non-vectorized fallback code to scan for length of an identifier.
  62. static constexpr std::array<bool, 256> IsIdByteTable = ([]() constexpr {
  63. std::array<bool, 256> table = {};
  64. for (char c = '0'; c <= '9'; ++c) {
  65. table[c] = true;
  66. }
  67. for (char c = 'A'; c <= 'Z'; ++c) {
  68. table[c] = true;
  69. }
  70. for (char c = 'a'; c <= 'z'; ++c) {
  71. table[c] = true;
  72. }
  73. table['_'] = true;
  74. return table;
  75. })();
  76. #if __x86_64__
  77. // This code uses a scheme derived from the techniques in Geoff Langdale and
  78. // Daniel Lemire's work on parsing JSON[1]. Specifically, that paper outlines
  79. // a technique of using two 4-bit indexed in-register look-up tables (LUTs) to
  80. // classify bytes in a branchless SIMD code sequence.
  81. //
  82. // [1]: https://arxiv.org/pdf/1902.08318.pdf
  83. //
  84. // The goal is to get a bit mask classifying different sets of bytes. For each
  85. // input byte, we first test for a high bit indicating a UTF-8 encoded Unicode
  86. // character. Otherwise, we want the mask bits to be set with the following
  87. // logic derived by inspecting the high nibble and low nibble of the input:
  88. // bit0 = 1 for `_`: high `0x5` and low `0xF`
  89. // bit1 = 1 for `0-9`: high `0x3` and low `0x0` - `0x9`
  90. // bit2 = 1 for `A-O` and `a-o`: high `0x4` or `0x6` and low `0x1` - `0xF`
  91. // bit3 = 1 for `P-Z` and 'p-z': high `0x5` or `0x7` and low `0x0` - `0xA`
  92. // bit4 = unused
  93. // bit5 = unused
  94. // bit6 = unused
  95. // bit7 = unused
  96. //
  97. // No bits set means definitively non-ID ASCII character.
  98. //
  99. // bits 4-7 remain unused if we need to classify more characters.
  100. const auto high_lut = _mm_setr_epi8(
  101. /* __b0=*/0b0000'0000,
  102. /* __b1=*/0b0000'0000,
  103. /* __b2=*/0b0000'0000,
  104. /* __b3=*/0b0000'0010,
  105. /* __b4=*/0b0000'0100,
  106. /* __b5=*/0b0000'1001,
  107. /* __b6=*/0b0000'0100,
  108. /* __b7=*/0b0000'1000,
  109. /* __b8=*/0b0000'0000,
  110. /* __b9=*/0b0000'0000,
  111. /*__b10=*/0b0000'0000,
  112. /*__b11=*/0b0000'0000,
  113. /*__b12=*/0b0000'0000,
  114. /*__b13=*/0b0000'0000,
  115. /*__b14=*/0b0000'0000,
  116. /*__b15=*/0b0000'0000);
  117. const auto low_lut = _mm_setr_epi8(
  118. /* __b0=*/0b0000'1010,
  119. /* __b1=*/0b0000'1110,
  120. /* __b2=*/0b0000'1110,
  121. /* __b3=*/0b0000'1110,
  122. /* __b4=*/0b0000'1110,
  123. /* __b5=*/0b0000'1110,
  124. /* __b6=*/0b0000'1110,
  125. /* __b7=*/0b0000'1110,
  126. /* __b8=*/0b0000'1110,
  127. /* __b9=*/0b0000'1110,
  128. /*__b10=*/0b0000'1100,
  129. /*__b11=*/0b0000'0100,
  130. /*__b12=*/0b0000'0100,
  131. /*__b13=*/0b0000'0100,
  132. /*__b14=*/0b0000'0100,
  133. /*__b15=*/0b0000'0101);
  134. // Use `ssize_t` for performance here as we index memory in a tight loop.
  135. ssize_t i = 0;
  136. const ssize_t size = text.size();
  137. while ((i + 16) <= size) {
  138. __m128i input =
  139. _mm_loadu_si128(reinterpret_cast<const __m128i*>(text.data() + i));
  140. // The high bits of each byte indicate a non-ASCII character encoded using
  141. // UTF-8. Test those and fall back to the scalar code if present. These
  142. // bytes will also cause spurious zeros in the LUT results, but we can
  143. // ignore that because we track them independently here.
  144. #if __SSE4_1__
  145. if (!_mm_test_all_zeros(_mm_set1_epi8(0x80), input)) {
  146. break;
  147. }
  148. #else
  149. if (_mm_movemask_epi8(input) != 0) {
  150. break;
  151. }
  152. #endif
  153. // Do two LUT lookups and mask the results together to get the results for
  154. // both low and high nibbles. Note that we don't need to mask out the high
  155. // bit of input here because we track that above for UTF-8 handling.
  156. __m128i low_mask = _mm_shuffle_epi8(low_lut, input);
  157. // Note that the input needs to be masked to only include the high nibble or
  158. // we could end up with bit7 set forcing the result to a zero byte.
  159. __m128i input_high =
  160. _mm_and_si128(_mm_srli_epi32(input, 4), _mm_set1_epi8(0x0f));
  161. __m128i high_mask = _mm_shuffle_epi8(high_lut, input_high);
  162. __m128i mask = _mm_and_si128(low_mask, high_mask);
  163. // Now compare to find the completely zero bytes.
  164. __m128i id_byte_mask_vec = _mm_cmpeq_epi8(mask, _mm_setzero_si128());
  165. int tail_ascii_mask = _mm_movemask_epi8(id_byte_mask_vec);
  166. // Check if there are bits in the tail mask, which means zero bytes and the
  167. // end of the identifier. We could do this without materializing the scalar
  168. // mask on more recent CPUs, but we generally expect the median length we
  169. // encounter to be <16 characters and so we avoid the extra instruction in
  170. // that case and predict this branch to succeed so it is laid out in a
  171. // reasonable way.
  172. if (LLVM_LIKELY(tail_ascii_mask != 0)) {
  173. // Move past the definitively classified bytes that are part of the
  174. // identifier, and return the complete identifier text.
  175. i += __builtin_ctz(tail_ascii_mask);
  176. return text.substr(0, i);
  177. }
  178. i += 16;
  179. }
  180. // Fallback to scalar loop. We only end up here when we don't have >=16
  181. // bytes to scan or we find a UTF-8 unicode character.
  182. // TODO: This assumes all Unicode characters are non-identifiers.
  183. while (i < size && IsIdByteTable[static_cast<unsigned char>(text[i])]) {
  184. ++i;
  185. }
  186. return text.substr(0, i);
  187. #else
  188. // TODO: Optimize this with SIMD for other architectures.
  189. return text.take_while(
  190. [](char c) { return IsIdByteTable[static_cast<unsigned char>(c)]; });
  191. #endif
  192. }
  193. // Implementation of the lexer logic itself.
  194. //
  195. // The design is that lexing can loop over the source buffer, consuming it into
  196. // tokens by calling into this API. This class handles the state and breaks down
  197. // the different lexing steps that may be used. It directly updates the provided
  198. // tokenized buffer with the lexed tokens.
  199. class [[clang::internal_linkage]] TokenizedBuffer::Lexer {
  200. public:
  201. // Symbolic result of a lexing action. This indicates whether we successfully
  202. // lexed a token, or whether other lexing actions should be attempted.
  203. //
  204. // While it wraps a simple boolean state, its API both helps make the failures
  205. // more self documenting, and by consuming the actual token constructively
  206. // when one is produced, it helps ensure the correct result is returned.
  207. class LexResult {
  208. public:
  209. // Consumes (and discard) a valid token to construct a result
  210. // indicating a token has been produced. Relies on implicit conversions.
  211. // NOLINTNEXTLINE(google-explicit-constructor)
  212. LexResult(Token /*discarded_token*/) : LexResult(true) {}
  213. // Returns a result indicating no token was produced.
  214. static auto NoMatch() -> LexResult { return LexResult(false); }
  215. // Tests whether a token was produced by the lexing routine, and
  216. // the lexer can continue forming tokens.
  217. explicit operator bool() const { return formed_token_; }
  218. private:
  219. explicit LexResult(bool formed_token) : formed_token_(formed_token) {}
  220. bool formed_token_;
  221. };
  222. Lexer(TokenizedBuffer& buffer, DiagnosticConsumer& consumer)
  223. : buffer_(&buffer),
  224. translator_(&buffer),
  225. emitter_(translator_, consumer),
  226. token_translator_(&buffer),
  227. token_emitter_(token_translator_, consumer) {}
  228. // Find all line endings and create the line data structures. Explicitly kept
  229. // out-of-line because this is a significant loop that is useful to have in
  230. // the profile and it doesn't simplify by inlining at all. But because it can,
  231. // the compiler will flatten this otherwise.
  232. [[gnu::noinline]] auto CreateLines(llvm::StringRef source_text) -> void {
  233. // We currently use `memchr` here which typically is well optimized to use
  234. // SIMD or other significantly faster than byte-wise scanning. We also use
  235. // carefully selected variables and the `ssize_t` type for performance and
  236. // code size of this hot loop.
  237. //
  238. // TODO: Eventually, we'll likely need to roll our own SIMD-optimized
  239. // routine here in order to handle CR+LF line endings, as we'll want those
  240. // to stay on the fast path. We'll also need to detect and diagnose Unicode
  241. // vertical whitespace. Starting with `memchr` should give us a strong
  242. // baseline performance target when adding those features.
  243. const char* const text = source_text.data();
  244. const ssize_t size = source_text.size();
  245. ssize_t start = 0;
  246. while (const char* nl = reinterpret_cast<const char*>(
  247. memchr(&text[start], '\n', size - start))) {
  248. ssize_t nl_index = nl - text;
  249. buffer_->AddLine(LineInfo(start, nl_index - start));
  250. start = nl_index + 1;
  251. }
  252. // The last line ends at the end of the file.
  253. buffer_->AddLine(LineInfo(start, size - start));
  254. // Now that all the infos are allocated, get a fresh pointer to the first
  255. // info for use while lexing.
  256. current_line_ = Line(0);
  257. current_line_info_ = &buffer_->GetLineInfo(current_line_);
  258. }
  259. // Perform the necessary bookkeeping to step past a newline at the current
  260. // line and column.
  261. auto HandleNewline() -> void {
  262. int next_start = current_line_info_->start + current_column_ + 1;
  263. current_line_ = buffer_->GetNextLine(current_line_);
  264. current_line_info_ = &buffer_->GetLineInfo(current_line_);
  265. CARBON_DCHECK(next_start == current_line_info_->start);
  266. current_column_ = 0;
  267. set_indent_ = false;
  268. }
  269. auto NoteWhitespace() -> void {
  270. buffer_->token_infos_.back().has_trailing_space = true;
  271. }
  272. auto LexHorizontalWhitespace(llvm::StringRef& source_text) -> void {
  273. CARBON_DCHECK(source_text.front() == ' ' || source_text.front() == '\t');
  274. NoteWhitespace();
  275. ++current_column_;
  276. source_text = source_text.drop_front();
  277. }
  278. auto LexVerticalWhitespace(llvm::StringRef& source_text) -> void {
  279. CARBON_DCHECK(source_text.front() == '\n');
  280. NoteWhitespace();
  281. source_text = source_text.drop_front();
  282. HandleNewline();
  283. }
  284. auto LexCommentOrSlash(llvm::StringRef& source_text) -> void {
  285. CARBON_DCHECK(source_text.front() == '/');
  286. // Both comments and slash symbols start with a `/`. We disambiguate with a
  287. // max-munch rule -- if the next character is another `/` then we lex it as
  288. // a comment start. If it isn't, then we lex as a slash.
  289. if (source_text.size() > 1 && source_text[1] == '/') {
  290. LexComment(source_text);
  291. return;
  292. }
  293. // This code path should produce a token, make sure that happens.
  294. LexResult result = LexSymbolToken(source_text);
  295. CARBON_CHECK(result) << "Failed to form a token!";
  296. }
  297. auto LexComment(llvm::StringRef& source_text) -> void {
  298. CARBON_DCHECK(source_text.startswith("//"));
  299. // Any comment must be the only non-whitespace on the line.
  300. if (set_indent_) {
  301. CARBON_DIAGNOSTIC(TrailingComment, Error,
  302. "Trailing comments are not permitted.");
  303. emitter_.Emit(source_text.begin(), TrailingComment);
  304. }
  305. // The introducer '//' must be followed by whitespace or EOF.
  306. if (source_text.size() > 2 && !IsSpace(source_text[2])) {
  307. CARBON_DIAGNOSTIC(NoWhitespaceAfterCommentIntroducer, Error,
  308. "Whitespace is required after '//'.");
  309. emitter_.Emit(source_text.begin() + 2,
  310. NoWhitespaceAfterCommentIntroducer);
  311. }
  312. // Use the current line info to jump to the end of the line.
  313. source_text =
  314. source_text.drop_front(current_line_info_->length - current_column_);
  315. // This may be the end of the file in which case we immediately return.
  316. if (source_text.empty()) {
  317. // Finished lexing.
  318. return;
  319. }
  320. // Otherwise, lex the newline.
  321. current_column_ = current_line_info_->length;
  322. LexVerticalWhitespace(source_text);
  323. }
  324. auto LexNumericLiteral(llvm::StringRef& source_text) -> LexResult {
  325. std::optional<NumericLiteral> literal = NumericLiteral::Lex(source_text);
  326. if (!literal) {
  327. return LexError(source_text);
  328. }
  329. int int_column = current_column_;
  330. int token_size = literal->text().size();
  331. current_column_ += token_size;
  332. source_text = source_text.drop_front(token_size);
  333. if (!set_indent_) {
  334. current_line_info_->indent = int_column;
  335. set_indent_ = true;
  336. }
  337. return VariantMatch(
  338. literal->ComputeValue(emitter_),
  339. [&](NumericLiteral::IntegerValue&& value) {
  340. auto token = buffer_->AddToken({.kind = TokenKind::IntegerLiteral,
  341. .token_line = current_line_,
  342. .column = int_column});
  343. buffer_->GetTokenInfo(token).literal_index =
  344. buffer_->literal_int_storage_.size();
  345. buffer_->literal_int_storage_.push_back(std::move(value.value));
  346. return token;
  347. },
  348. [&](NumericLiteral::RealValue&& value) {
  349. auto token = buffer_->AddToken({.kind = TokenKind::RealLiteral,
  350. .token_line = current_line_,
  351. .column = int_column});
  352. buffer_->GetTokenInfo(token).literal_index =
  353. buffer_->literal_int_storage_.size();
  354. buffer_->literal_int_storage_.push_back(std::move(value.mantissa));
  355. buffer_->literal_int_storage_.push_back(std::move(value.exponent));
  356. CARBON_CHECK(buffer_->GetRealLiteral(token).is_decimal ==
  357. (value.radix == NumericLiteral::Radix::Decimal));
  358. return token;
  359. },
  360. [&](NumericLiteral::UnrecoverableError) {
  361. auto token = buffer_->AddToken({
  362. .kind = TokenKind::Error,
  363. .token_line = current_line_,
  364. .column = int_column,
  365. .error_length = token_size,
  366. });
  367. return token;
  368. });
  369. }
  370. auto LexStringLiteral(llvm::StringRef& source_text) -> LexResult {
  371. std::optional<StringLiteral> literal = StringLiteral::Lex(source_text);
  372. if (!literal) {
  373. return LexError(source_text);
  374. }
  375. Line string_line = current_line_;
  376. int string_column = current_column_;
  377. int literal_size = literal->text().size();
  378. source_text = source_text.drop_front(literal_size);
  379. if (!set_indent_) {
  380. current_line_info_->indent = string_column;
  381. set_indent_ = true;
  382. }
  383. // Update line and column information.
  384. if (!literal->is_multi_line()) {
  385. current_column_ += literal_size;
  386. } else {
  387. for (char c : literal->text()) {
  388. if (c == '\n') {
  389. HandleNewline();
  390. // The indentation of all lines in a multi-line string literal is
  391. // that of the first line.
  392. current_line_info_->indent = string_column;
  393. set_indent_ = true;
  394. } else {
  395. ++current_column_;
  396. }
  397. }
  398. }
  399. if (literal->is_terminated()) {
  400. auto token =
  401. buffer_->AddToken({.kind = TokenKind::StringLiteral,
  402. .token_line = string_line,
  403. .column = string_column,
  404. .literal_index = static_cast<int32_t>(
  405. buffer_->literal_string_storage_.size())});
  406. buffer_->literal_string_storage_.push_back(
  407. literal->ComputeValue(emitter_));
  408. return token;
  409. } else {
  410. CARBON_DIAGNOSTIC(UnterminatedString, Error,
  411. "String is missing a terminator.");
  412. emitter_.Emit(literal->text().begin(), UnterminatedString);
  413. return buffer_->AddToken({.kind = TokenKind::Error,
  414. .token_line = string_line,
  415. .column = string_column,
  416. .error_length = literal_size});
  417. }
  418. }
  419. auto LexSymbolToken(llvm::StringRef& source_text,
  420. TokenKind kind = TokenKind::Error) -> LexResult {
  421. auto compute_symbol_kind = [](llvm::StringRef source_text) {
  422. return llvm::StringSwitch<TokenKind>(source_text)
  423. #define CARBON_SYMBOL_TOKEN(Name, Spelling) \
  424. .StartsWith(Spelling, TokenKind::Name)
  425. #include "toolchain/lex/token_kind.def"
  426. .Default(TokenKind::Error);
  427. };
  428. // We use the `error` token as a place-holder for cases where one character
  429. // isn't enough to pick a definitive symbol token. Recompute the kind using
  430. // the full symbol set.
  431. if (LLVM_UNLIKELY(kind == TokenKind::Error)) {
  432. kind = compute_symbol_kind(source_text);
  433. if (kind == TokenKind::Error) {
  434. return LexError(source_text);
  435. }
  436. } else {
  437. // Verify in a debug build that the incoming token kind is correct.
  438. CARBON_DCHECK(kind == compute_symbol_kind(source_text))
  439. << "Incoming token kind '" << kind
  440. << "' does not match computed kind '"
  441. << compute_symbol_kind(source_text) << "'!";
  442. }
  443. if (!set_indent_) {
  444. current_line_info_->indent = current_column_;
  445. set_indent_ = true;
  446. }
  447. CloseInvalidOpenGroups(kind);
  448. const char* location = source_text.begin();
  449. Token token = buffer_->AddToken(
  450. {.kind = kind, .token_line = current_line_, .column = current_column_});
  451. current_column_ += kind.fixed_spelling().size();
  452. source_text = source_text.drop_front(kind.fixed_spelling().size());
  453. // Opening symbols just need to be pushed onto our queue of opening groups.
  454. if (kind.is_opening_symbol()) {
  455. open_groups_.push_back(token);
  456. return token;
  457. }
  458. // Only closing symbols need further special handling.
  459. if (!kind.is_closing_symbol()) {
  460. return token;
  461. }
  462. TokenInfo& closing_token_info = buffer_->GetTokenInfo(token);
  463. // Check that there is a matching opening symbol before we consume this as
  464. // a closing symbol.
  465. if (open_groups_.empty()) {
  466. closing_token_info.kind = TokenKind::Error;
  467. closing_token_info.error_length = kind.fixed_spelling().size();
  468. CARBON_DIAGNOSTIC(
  469. UnmatchedClosing, Error,
  470. "Closing symbol without a corresponding opening symbol.");
  471. emitter_.Emit(location, UnmatchedClosing);
  472. // Note that this still returns true as we do consume a symbol.
  473. return token;
  474. }
  475. // Finally can handle a normal closing symbol.
  476. Token opening_token = open_groups_.pop_back_val();
  477. TokenInfo& opening_token_info = buffer_->GetTokenInfo(opening_token);
  478. opening_token_info.closing_token = token;
  479. closing_token_info.opening_token = opening_token;
  480. return token;
  481. }
  482. // Given a word that has already been lexed, determine whether it is a type
  483. // literal and if so form the corresponding token.
  484. auto LexWordAsTypeLiteralToken(llvm::StringRef word, int column)
  485. -> LexResult {
  486. if (word.size() < 2) {
  487. // Too short to form one of these tokens.
  488. return LexResult::NoMatch();
  489. }
  490. if (word[1] < '1' || word[1] > '9') {
  491. // Doesn't start with a valid initial digit.
  492. return LexResult::NoMatch();
  493. }
  494. std::optional<TokenKind> kind;
  495. switch (word.front()) {
  496. case 'i':
  497. kind = TokenKind::IntegerTypeLiteral;
  498. break;
  499. case 'u':
  500. kind = TokenKind::UnsignedIntegerTypeLiteral;
  501. break;
  502. case 'f':
  503. kind = TokenKind::FloatingPointTypeLiteral;
  504. break;
  505. default:
  506. return LexResult::NoMatch();
  507. };
  508. llvm::StringRef suffix = word.substr(1);
  509. if (!CanLexInteger(emitter_, suffix)) {
  510. return buffer_->AddToken(
  511. {.kind = TokenKind::Error,
  512. .token_line = current_line_,
  513. .column = column,
  514. .error_length = static_cast<int32_t>(word.size())});
  515. }
  516. llvm::APInt suffix_value;
  517. if (suffix.getAsInteger(10, suffix_value)) {
  518. return LexResult::NoMatch();
  519. }
  520. auto token = buffer_->AddToken(
  521. {.kind = *kind, .token_line = current_line_, .column = column});
  522. buffer_->GetTokenInfo(token).literal_index =
  523. buffer_->literal_int_storage_.size();
  524. buffer_->literal_int_storage_.push_back(std::move(suffix_value));
  525. return token;
  526. }
  527. // Closes all open groups that cannot remain open across the symbol `K`.
  528. // Users may pass `Error` to close all open groups.
  529. auto CloseInvalidOpenGroups(TokenKind kind) -> void {
  530. // There are two common cases that result in nothing to close. Short circuit
  531. // those here.
  532. if ((!kind.is_closing_symbol() && kind != TokenKind::Error) ||
  533. open_groups_.empty()) {
  534. return;
  535. }
  536. // Also check the first open group token to see if it matches this closing
  537. // token, in which case there is nothing to do. This is redundant with the
  538. // work inside the main loop, but we peel it out to allow inlining.
  539. Token opening_token = open_groups_.back();
  540. TokenKind opening_kind = buffer_->GetTokenInfo(opening_token).kind;
  541. if (kind == opening_kind.closing_symbol()) {
  542. return;
  543. }
  544. // Otherwise, delegate to a separate function to help with inlining.
  545. CloseInvalidOpenGroupsSlow(kind);
  546. }
  547. [[gnu::noinline]] auto CloseInvalidOpenGroupsSlow(TokenKind kind) -> void {
  548. CARBON_CHECK(kind.is_closing_symbol() || kind == TokenKind::Error);
  549. CARBON_CHECK(!open_groups_.empty());
  550. do {
  551. Token opening_token = open_groups_.back();
  552. TokenKind opening_kind = buffer_->GetTokenInfo(opening_token).kind;
  553. if (kind == opening_kind.closing_symbol()) {
  554. return;
  555. }
  556. open_groups_.pop_back();
  557. CARBON_DIAGNOSTIC(
  558. MismatchedClosing, Error,
  559. "Closing symbol does not match most recent opening symbol.");
  560. token_emitter_.Emit(opening_token, MismatchedClosing);
  561. CARBON_CHECK(!buffer_->tokens().empty())
  562. << "Must have a prior opening token!";
  563. Token prev_token = buffer_->tokens().end()[-1];
  564. // TODO: do a smarter backwards scan for where to put the closing
  565. // token.
  566. Token closing_token = buffer_->AddToken(
  567. {.kind = opening_kind.closing_symbol(),
  568. .has_trailing_space = buffer_->HasTrailingWhitespace(prev_token),
  569. .is_recovery = true,
  570. .token_line = current_line_,
  571. .column = current_column_});
  572. TokenInfo& opening_token_info = buffer_->GetTokenInfo(opening_token);
  573. TokenInfo& closing_token_info = buffer_->GetTokenInfo(closing_token);
  574. opening_token_info.closing_token = closing_token;
  575. closing_token_info.opening_token = opening_token;
  576. } while (!open_groups_.empty());
  577. }
  578. auto GetOrCreateIdentifier(llvm::StringRef text) -> Identifier {
  579. auto insert_result = buffer_->identifier_map_.insert(
  580. {text, Identifier(buffer_->identifier_infos_.size())});
  581. if (insert_result.second) {
  582. buffer_->identifier_infos_.push_back({text});
  583. }
  584. return insert_result.first->second;
  585. }
  586. auto LexKeywordOrIdentifier(llvm::StringRef& source_text) -> LexResult {
  587. if (static_cast<unsigned char>(source_text.front()) > 0x7F) {
  588. // TODO: Need to add support for Unicode lexing.
  589. return LexError(source_text);
  590. }
  591. CARBON_CHECK(IsAlpha(source_text.front()) || source_text.front() == '_');
  592. if (!set_indent_) {
  593. current_line_info_->indent = current_column_;
  594. set_indent_ = true;
  595. }
  596. // Take the valid characters off the front of the source buffer.
  597. llvm::StringRef identifier_text = ScanForIdentifierPrefix(source_text);
  598. CARBON_CHECK(!identifier_text.empty())
  599. << "Must have at least one character!";
  600. int identifier_column = current_column_;
  601. current_column_ += identifier_text.size();
  602. source_text = source_text.drop_front(identifier_text.size());
  603. // Check if the text is a type literal, and if so form such a literal.
  604. if (LexResult result =
  605. LexWordAsTypeLiteralToken(identifier_text, identifier_column)) {
  606. return result;
  607. }
  608. // Check if the text matches a keyword token, and if so use that.
  609. TokenKind kind = llvm::StringSwitch<TokenKind>(identifier_text)
  610. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, TokenKind::Name)
  611. #include "toolchain/lex/token_kind.def"
  612. .Default(TokenKind::Error);
  613. if (kind != TokenKind::Error) {
  614. return buffer_->AddToken({.kind = kind,
  615. .token_line = current_line_,
  616. .column = identifier_column});
  617. }
  618. // Otherwise we have a generic identifier.
  619. return buffer_->AddToken({.kind = TokenKind::Identifier,
  620. .token_line = current_line_,
  621. .column = identifier_column,
  622. .id = GetOrCreateIdentifier(identifier_text)});
  623. }
  624. auto LexError(llvm::StringRef& source_text) -> LexResult {
  625. llvm::StringRef error_text = source_text.take_while([](char c) {
  626. if (IsAlnum(c)) {
  627. return false;
  628. }
  629. switch (c) {
  630. case '_':
  631. case '\t':
  632. case '\n':
  633. return false;
  634. default:
  635. break;
  636. }
  637. return llvm::StringSwitch<bool>(llvm::StringRef(&c, 1))
  638. #define CARBON_SYMBOL_TOKEN(Name, Spelling) .StartsWith(Spelling, false)
  639. #include "toolchain/lex/token_kind.def"
  640. .Default(true);
  641. });
  642. if (error_text.empty()) {
  643. // TODO: Reimplement this to use the lexer properly. In the meantime,
  644. // guarantee that we eat at least one byte.
  645. error_text = source_text.take_front(1);
  646. }
  647. auto token = buffer_->AddToken(
  648. {.kind = TokenKind::Error,
  649. .token_line = current_line_,
  650. .column = current_column_,
  651. .error_length = static_cast<int32_t>(error_text.size())});
  652. CARBON_DIAGNOSTIC(UnrecognizedCharacters, Error,
  653. "Encountered unrecognized characters while parsing.");
  654. emitter_.Emit(error_text.begin(), UnrecognizedCharacters);
  655. current_column_ += error_text.size();
  656. source_text = source_text.drop_front(error_text.size());
  657. return token;
  658. }
  659. auto LexStartOfFile(llvm::StringRef& /*source_text*/) -> void {
  660. // Before lexing any source text, add the start-of-file token so that code
  661. // can assume a non-empty token buffer for the rest of lexing. Note that the
  662. // start-of-file always has trailing space because it *is* whitespace.
  663. buffer_->AddToken({.kind = TokenKind::StartOfFile,
  664. .has_trailing_space = true,
  665. .token_line = current_line_,
  666. .column = current_column_});
  667. }
  668. auto LexEndOfFile(llvm::StringRef& source_text) -> void {
  669. CARBON_DCHECK(source_text.empty());
  670. // Check if the last line is empty and not the first line (and only). If so,
  671. // re-pin the last line to be the prior one so that diagnostics and editors
  672. // can treat newlines as terminators even though we internally handle them
  673. // as separators in case of a missing newline on the last line. We do this
  674. // here instead of detecting this when we see the newline to avoid more
  675. // conditions along that fast path.
  676. if (current_column_ == 0 && buffer_->GetLineNumber(current_line_) != 1) {
  677. current_line_ = buffer_->GetPrevLine(current_line_);
  678. current_line_info_ = &buffer_->GetLineInfo(current_line_);
  679. current_column_ = current_line_info_->length;
  680. } else {
  681. // Update the line length as this is also the end of a line.
  682. current_line_info_->length = current_column_;
  683. }
  684. // The end-of-file token is always considered to be whitespace.
  685. NoteWhitespace();
  686. // Close any open groups. We do this after marking whitespace, it will
  687. // preserve that.
  688. CloseInvalidOpenGroups(TokenKind::Error);
  689. buffer_->AddToken({.kind = TokenKind::EndOfFile,
  690. .token_line = current_line_,
  691. .column = current_column_});
  692. }
  693. // We use a collection of static member functions for table-based dispatch to
  694. // lexer methods. These are named static member functions so that they show up
  695. // helpfully in profiles and backtraces, but they tend to not contain the
  696. // interesting logic and simply delegate to the relevant methods. All of their
  697. // signatures need to be exactly the same however in order to ensure we can
  698. // build efficient dispatch tables out of them. All of them end by doing a
  699. // must-tail return call to this routine. It handles continuing the dispatch
  700. // chain.
  701. static auto DispatchNext(Lexer& lexer, llvm::StringRef& source_text) -> void {
  702. // When we finish the source text, stop recursing. We also hint this so that
  703. // the tail-dispatch is optimized as that's essentially the loop back-edge
  704. // and this is the loop exit.
  705. if (LLVM_UNLIKELY(source_text.empty())) {
  706. lexer.LexEndOfFile(source_text);
  707. return;
  708. }
  709. // The common case is to tail recurse based on the next character. Note that
  710. // because this is a must-tail return, this cannot fail to tail-call and
  711. // will not grow the stack. This is in essence a loop with dynamic tail
  712. // dispatch to the next stage of the loop.
  713. [[clang::musttail]] return DispatchTable[static_cast<unsigned char>(
  714. source_text.front())](lexer, source_text);
  715. }
  716. // Define a set of dispatch functions that simply forward to a method that
  717. // lexes a token. This includes validating that an actual token was produced,
  718. // and continuing the dispatch.
  719. #define CARBON_DISPATCH_LEX_TOKEN(LexMethod) \
  720. static auto Dispatch##LexMethod(Lexer& lexer, llvm::StringRef& source_text) \
  721. ->void { \
  722. LexResult result = lexer.LexMethod(source_text); \
  723. CARBON_CHECK(result) << "Failed to form a token!"; \
  724. [[clang::musttail]] return DispatchNext(lexer, source_text); \
  725. }
  726. CARBON_DISPATCH_LEX_TOKEN(LexError)
  727. CARBON_DISPATCH_LEX_TOKEN(LexSymbolToken)
  728. CARBON_DISPATCH_LEX_TOKEN(LexKeywordOrIdentifier)
  729. CARBON_DISPATCH_LEX_TOKEN(LexNumericLiteral)
  730. CARBON_DISPATCH_LEX_TOKEN(LexStringLiteral)
  731. // A custom dispatch function that pre-selects a symbol token to lex.
  732. template <const TokenKind& Token>
  733. static auto DispatchLexOneCharSymbol(Lexer& lexer,
  734. llvm::StringRef& source_text) -> void {
  735. LexResult result = lexer.LexSymbolToken(source_text, Token);
  736. CARBON_CHECK(result) << "Failed to form a token!";
  737. [[clang::musttail]] return DispatchNext(lexer, source_text);
  738. }
  739. // Define a set of non-token dispatch functions that handle things like
  740. // whitespace and comments.
  741. #define CARBON_DISPATCH_LEX_NON_TOKEN(LexMethod) \
  742. static auto Dispatch##LexMethod(Lexer& lexer, llvm::StringRef& source_text) \
  743. ->void { \
  744. lexer.LexMethod(source_text); \
  745. [[clang::musttail]] return DispatchNext(lexer, source_text); \
  746. }
  747. CARBON_DISPATCH_LEX_NON_TOKEN(LexHorizontalWhitespace)
  748. CARBON_DISPATCH_LEX_NON_TOKEN(LexVerticalWhitespace)
  749. CARBON_DISPATCH_LEX_NON_TOKEN(LexCommentOrSlash)
  750. // The main entry point for dispatching through the lexer's table. This method
  751. // should always fully consume the source text.
  752. auto Dispatch(llvm::StringRef& source_text) -> void {
  753. // First build up our line data structures.
  754. CreateLines(source_text);
  755. LexStartOfFile(source_text);
  756. // Manually enter the dispatch loop. This call will tail-recurse through the
  757. // dispatch table until everything from source_text is consumed.
  758. DispatchNext(*this, source_text);
  759. CARBON_CHECK(source_text.empty())
  760. << "Finished lexer dispatch without consuming the entire source text!";
  761. }
  762. private:
  763. using DispatchFunctionT = auto(Lexer& lexer, llvm::StringRef& source_text)
  764. -> void;
  765. using DispatchTableT = std::array<DispatchFunctionT*, 256>;
  766. // Build a table of function pointers that we can use to dispatch to the
  767. // correct lexer routine based on the first byte of source text.
  768. //
  769. // While it is tempting to simply use a `switch` on the first byte and
  770. // dispatch with cases into this, in practice that doesn't produce great code.
  771. // There seem to be two issues that are the root cause.
  772. //
  773. // First, there are lots of different values of bytes that dispatch to a
  774. // fairly small set of routines, and then some byte values that dispatch
  775. // differently for each byte. This pattern isn't one that the compiler-based
  776. // lowering of switches works well with -- it tries to balance all the cases,
  777. // and in doing so emits several compares and other control flow rather than a
  778. // simple jump table.
  779. //
  780. // Second, with a `case`, it isn't as obvious how to create a single, uniform
  781. // interface that is effective for *every* byte value, and thus makes for a
  782. // single consistent table-based dispatch. By forcing these to be function
  783. // pointers, we also coerce the code to use a strictly homogeneous structure
  784. // that can form a single dispatch table.
  785. //
  786. // These two actually interact -- the second issue is part of what makes the
  787. // non-table lowering in the first one desirable for many switches and cases.
  788. //
  789. // Ultimately, when table-based dispatch is such an important technique, we
  790. // get better results by taking full control and manually creating the
  791. // dispatch structures.
  792. //
  793. // The functions in this table also use tail-recursion to implement the loop
  794. // of the lexer. This is based on the technique described more fully for any
  795. // kind of byte-stream loop structure here:
  796. // https://blog.reverberate.org/2021/04/21/musttail-efficient-interpreters.html
  797. constexpr static auto MakeDispatchTable() -> DispatchTableT {
  798. DispatchTableT table = {};
  799. // First set the table entries to dispatch to our error token handler as the
  800. // base case. Everything valid comes from an override below.
  801. for (int i = 0; i < 256; ++i) {
  802. table[i] = &DispatchLexError;
  803. }
  804. // Symbols have some special dispatching. First, set the first character of
  805. // each symbol token spelling to dispatch to the symbol lexer. We don't
  806. // provide a pre-computed token here, so the symbol lexer will compute the
  807. // exact symbol token kind. We'll override this with more specific dispatch
  808. // below.
  809. #define CARBON_SYMBOL_TOKEN(TokenName, Spelling) \
  810. table[(Spelling)[0]] = &DispatchLexSymbolToken;
  811. #include "toolchain/lex/token_kind.def"
  812. // Now special cased single-character symbols that are guaranteed to not
  813. // join with another symbol. These are grouping symbols, terminators,
  814. // or separators in the grammar and have a good reason to be
  815. // orthogonal to any other punctuation. We do this separately because this
  816. // needs to override some of the generic handling above, and provide a
  817. // custom token.
  818. #define CARBON_ONE_CHAR_SYMBOL_TOKEN(TokenName, Spelling) \
  819. table[(Spelling)[0]] = &DispatchLexOneCharSymbol<TokenKind::TokenName>;
  820. #include "toolchain/lex/token_kind.def"
  821. // Override the handling for `/` to consider comments as well as a `/`
  822. // symbol.
  823. table['/'] = &DispatchLexCommentOrSlash;
  824. table['_'] = &DispatchLexKeywordOrIdentifier;
  825. // Note that we don't use `llvm::seq` because this needs to be `constexpr`
  826. // evaluated.
  827. for (unsigned char c = 'a'; c <= 'z'; ++c) {
  828. table[c] = &DispatchLexKeywordOrIdentifier;
  829. }
  830. for (unsigned char c = 'A'; c <= 'Z'; ++c) {
  831. table[c] = &DispatchLexKeywordOrIdentifier;
  832. }
  833. // We dispatch all non-ASCII UTF-8 characters to the identifier lexing
  834. // as whitespace characters should already have been skipped and the
  835. // only remaining valid Unicode characters would be part of an
  836. // identifier. That code can either accept or reject.
  837. for (int i = 0x80; i < 0x100; ++i) {
  838. table[i] = &DispatchLexKeywordOrIdentifier;
  839. }
  840. for (unsigned char c = '0'; c <= '9'; ++c) {
  841. table[c] = &DispatchLexNumericLiteral;
  842. }
  843. table['\''] = &DispatchLexStringLiteral;
  844. table['"'] = &DispatchLexStringLiteral;
  845. table['#'] = &DispatchLexStringLiteral;
  846. table[' '] = &DispatchLexHorizontalWhitespace;
  847. table['\t'] = &DispatchLexHorizontalWhitespace;
  848. table['\n'] = &DispatchLexVerticalWhitespace;
  849. return table;
  850. };
  851. static const DispatchTableT DispatchTable;
  852. TokenizedBuffer* buffer_;
  853. SourceBufferLocationTranslator translator_;
  854. LexerDiagnosticEmitter emitter_;
  855. TokenLocationTranslator token_translator_;
  856. TokenDiagnosticEmitter token_emitter_;
  857. Line current_line_ = Line::Invalid;
  858. LineInfo* current_line_info_;
  859. int current_column_ = 0;
  860. bool set_indent_ = false;
  861. llvm::SmallVector<Token> open_groups_;
  862. };
  863. constexpr TokenizedBuffer::Lexer::DispatchTableT
  864. TokenizedBuffer::Lexer::DispatchTable = MakeDispatchTable();
  865. auto TokenizedBuffer::Lex(SourceBuffer& source, DiagnosticConsumer& consumer)
  866. -> TokenizedBuffer {
  867. TokenizedBuffer buffer(source);
  868. ErrorTrackingDiagnosticConsumer error_tracking_consumer(consumer);
  869. Lexer lexer(buffer, error_tracking_consumer);
  870. llvm::StringRef source_text = source.text();
  871. lexer.Dispatch(source_text);
  872. if (error_tracking_consumer.seen_error()) {
  873. buffer.has_errors_ = true;
  874. }
  875. return buffer;
  876. }
  877. auto TokenizedBuffer::GetKind(Token token) const -> TokenKind {
  878. return GetTokenInfo(token).kind;
  879. }
  880. auto TokenizedBuffer::GetLine(Token token) const -> Line {
  881. return GetTokenInfo(token).token_line;
  882. }
  883. auto TokenizedBuffer::GetLineNumber(Token token) const -> int {
  884. return GetLineNumber(GetLine(token));
  885. }
  886. auto TokenizedBuffer::GetColumnNumber(Token token) const -> int {
  887. return GetTokenInfo(token).column + 1;
  888. }
  889. auto TokenizedBuffer::GetTokenText(Token token) const -> llvm::StringRef {
  890. const auto& token_info = GetTokenInfo(token);
  891. llvm::StringRef fixed_spelling = token_info.kind.fixed_spelling();
  892. if (!fixed_spelling.empty()) {
  893. return fixed_spelling;
  894. }
  895. if (token_info.kind == TokenKind::Error) {
  896. const auto& line_info = GetLineInfo(token_info.token_line);
  897. int64_t token_start = line_info.start + token_info.column;
  898. return source_->text().substr(token_start, token_info.error_length);
  899. }
  900. // Refer back to the source text to preserve oddities like radix or digit
  901. // separators the author included.
  902. if (token_info.kind == TokenKind::IntegerLiteral ||
  903. token_info.kind == TokenKind::RealLiteral) {
  904. const auto& line_info = GetLineInfo(token_info.token_line);
  905. int64_t token_start = line_info.start + token_info.column;
  906. std::optional<NumericLiteral> relexed_token =
  907. NumericLiteral::Lex(source_->text().substr(token_start));
  908. CARBON_CHECK(relexed_token) << "Could not reform numeric literal token.";
  909. return relexed_token->text();
  910. }
  911. // Refer back to the source text to find the original spelling, including
  912. // escape sequences etc.
  913. if (token_info.kind == TokenKind::StringLiteral) {
  914. const auto& line_info = GetLineInfo(token_info.token_line);
  915. int64_t token_start = line_info.start + token_info.column;
  916. std::optional<StringLiteral> relexed_token =
  917. StringLiteral::Lex(source_->text().substr(token_start));
  918. CARBON_CHECK(relexed_token) << "Could not reform string literal token.";
  919. return relexed_token->text();
  920. }
  921. // Refer back to the source text to avoid needing to reconstruct the
  922. // spelling from the size.
  923. if (token_info.kind.is_sized_type_literal()) {
  924. const auto& line_info = GetLineInfo(token_info.token_line);
  925. int64_t token_start = line_info.start + token_info.column;
  926. llvm::StringRef suffix =
  927. source_->text().substr(token_start + 1).take_while(IsDecimalDigit);
  928. return llvm::StringRef(suffix.data() - 1, suffix.size() + 1);
  929. }
  930. if (token_info.kind == TokenKind::StartOfFile ||
  931. token_info.kind == TokenKind::EndOfFile) {
  932. return llvm::StringRef();
  933. }
  934. CARBON_CHECK(token_info.kind == TokenKind::Identifier) << token_info.kind;
  935. return GetIdentifierText(token_info.id);
  936. }
  937. auto TokenizedBuffer::GetIdentifier(Token token) const -> Identifier {
  938. const auto& token_info = GetTokenInfo(token);
  939. CARBON_CHECK(token_info.kind == TokenKind::Identifier) << token_info.kind;
  940. return token_info.id;
  941. }
  942. auto TokenizedBuffer::GetIntegerLiteral(Token token) const
  943. -> const llvm::APInt& {
  944. const auto& token_info = GetTokenInfo(token);
  945. CARBON_CHECK(token_info.kind == TokenKind::IntegerLiteral) << token_info.kind;
  946. return literal_int_storage_[token_info.literal_index];
  947. }
  948. auto TokenizedBuffer::GetRealLiteral(Token token) const -> RealLiteralValue {
  949. const auto& token_info = GetTokenInfo(token);
  950. CARBON_CHECK(token_info.kind == TokenKind::RealLiteral) << token_info.kind;
  951. // Note that every real literal is at least three characters long, so we can
  952. // safely look at the second character to determine whether we have a
  953. // decimal or hexadecimal literal.
  954. const auto& line_info = GetLineInfo(token_info.token_line);
  955. int64_t token_start = line_info.start + token_info.column;
  956. char second_char = source_->text()[token_start + 1];
  957. bool is_decimal = second_char != 'x' && second_char != 'b';
  958. return {.mantissa = literal_int_storage_[token_info.literal_index],
  959. .exponent = literal_int_storage_[token_info.literal_index + 1],
  960. .is_decimal = is_decimal};
  961. }
  962. auto TokenizedBuffer::GetStringLiteral(Token token) const -> llvm::StringRef {
  963. const auto& token_info = GetTokenInfo(token);
  964. CARBON_CHECK(token_info.kind == TokenKind::StringLiteral) << token_info.kind;
  965. return literal_string_storage_[token_info.literal_index];
  966. }
  967. auto TokenizedBuffer::GetTypeLiteralSize(Token token) const
  968. -> const llvm::APInt& {
  969. const auto& token_info = GetTokenInfo(token);
  970. CARBON_CHECK(token_info.kind.is_sized_type_literal()) << token_info.kind;
  971. return literal_int_storage_[token_info.literal_index];
  972. }
  973. auto TokenizedBuffer::GetMatchedClosingToken(Token opening_token) const
  974. -> Token {
  975. const auto& opening_token_info = GetTokenInfo(opening_token);
  976. CARBON_CHECK(opening_token_info.kind.is_opening_symbol())
  977. << opening_token_info.kind;
  978. return opening_token_info.closing_token;
  979. }
  980. auto TokenizedBuffer::GetMatchedOpeningToken(Token closing_token) const
  981. -> Token {
  982. const auto& closing_token_info = GetTokenInfo(closing_token);
  983. CARBON_CHECK(closing_token_info.kind.is_closing_symbol())
  984. << closing_token_info.kind;
  985. return closing_token_info.opening_token;
  986. }
  987. auto TokenizedBuffer::HasLeadingWhitespace(Token token) const -> bool {
  988. auto it = TokenIterator(token);
  989. return it == tokens().begin() || GetTokenInfo(*(it - 1)).has_trailing_space;
  990. }
  991. auto TokenizedBuffer::HasTrailingWhitespace(Token token) const -> bool {
  992. return GetTokenInfo(token).has_trailing_space;
  993. }
  994. auto TokenizedBuffer::IsRecoveryToken(Token token) const -> bool {
  995. return GetTokenInfo(token).is_recovery;
  996. }
  997. auto TokenizedBuffer::GetLineNumber(Line line) const -> int {
  998. return line.index + 1;
  999. }
  1000. auto TokenizedBuffer::GetNextLine(Line line) const -> Line {
  1001. Line next(line.index + 1);
  1002. CARBON_DCHECK(static_cast<size_t>(next.index) < line_infos_.size());
  1003. return next;
  1004. }
  1005. auto TokenizedBuffer::GetPrevLine(Line line) const -> Line {
  1006. CARBON_CHECK(line.index > 0);
  1007. return Line(line.index - 1);
  1008. }
  1009. auto TokenizedBuffer::GetIndentColumnNumber(Line line) const -> int {
  1010. return GetLineInfo(line).indent + 1;
  1011. }
  1012. auto TokenizedBuffer::GetIdentifierText(Identifier identifier) const
  1013. -> llvm::StringRef {
  1014. return identifier_infos_[identifier.index].text;
  1015. }
  1016. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  1017. index = std::max(widths.index, index);
  1018. kind = std::max(widths.kind, kind);
  1019. column = std::max(widths.column, column);
  1020. line = std::max(widths.line, line);
  1021. indent = std::max(widths.indent, indent);
  1022. }
  1023. // Compute the printed width of a number. When numbers are printed in decimal,
  1024. // the number of digits needed is is one more than the log-base-10 of the
  1025. // value. We handle a value of `zero` explicitly.
  1026. //
  1027. // This routine requires its argument to be *non-negative*.
  1028. static auto ComputeDecimalPrintedWidth(int number) -> int {
  1029. CARBON_CHECK(number >= 0) << "Negative numbers are not supported.";
  1030. if (number == 0) {
  1031. return 1;
  1032. }
  1033. return static_cast<int>(std::log10(number)) + 1;
  1034. }
  1035. auto TokenizedBuffer::GetTokenPrintWidths(Token token) const -> PrintWidths {
  1036. PrintWidths widths = {};
  1037. widths.index = ComputeDecimalPrintedWidth(token_infos_.size());
  1038. widths.kind = GetKind(token).name().size();
  1039. widths.line = ComputeDecimalPrintedWidth(GetLineNumber(token));
  1040. widths.column = ComputeDecimalPrintedWidth(GetColumnNumber(token));
  1041. widths.indent =
  1042. ComputeDecimalPrintedWidth(GetIndentColumnNumber(GetLine(token)));
  1043. return widths;
  1044. }
  1045. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  1046. if (tokens().begin() == tokens().end()) {
  1047. return;
  1048. }
  1049. output_stream << "- filename: " << source_->filename() << "\n"
  1050. << " tokens: [\n";
  1051. PrintWidths widths = {};
  1052. widths.index = ComputeDecimalPrintedWidth((token_infos_.size()));
  1053. for (Token token : tokens()) {
  1054. widths.Widen(GetTokenPrintWidths(token));
  1055. }
  1056. for (Token token : tokens()) {
  1057. PrintToken(output_stream, token, widths);
  1058. output_stream << "\n";
  1059. }
  1060. output_stream << " ]\n";
  1061. }
  1062. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  1063. Token token) const -> void {
  1064. PrintToken(output_stream, token, {});
  1065. }
  1066. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, Token token,
  1067. PrintWidths widths) const -> void {
  1068. widths.Widen(GetTokenPrintWidths(token));
  1069. int token_index = token.index;
  1070. const auto& token_info = GetTokenInfo(token);
  1071. llvm::StringRef token_text = GetTokenText(token);
  1072. // Output the main chunk using one format string. We have to do the
  1073. // justification manually in order to use the dynamically computed widths
  1074. // and get the quotes included.
  1075. output_stream << llvm::formatv(
  1076. " { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  1077. "spelling: '{5}'",
  1078. llvm::format_decimal(token_index, widths.index),
  1079. llvm::right_justify(llvm::formatv("'{0}'", token_info.kind.name()).str(),
  1080. widths.kind + 2),
  1081. llvm::format_decimal(GetLineNumber(token_info.token_line), widths.line),
  1082. llvm::format_decimal(GetColumnNumber(token), widths.column),
  1083. llvm::format_decimal(GetIndentColumnNumber(token_info.token_line),
  1084. widths.indent),
  1085. token_text);
  1086. switch (token_info.kind) {
  1087. case TokenKind::Identifier:
  1088. output_stream << ", identifier: " << GetIdentifier(token).index;
  1089. break;
  1090. case TokenKind::IntegerLiteral:
  1091. output_stream << ", value: `";
  1092. GetIntegerLiteral(token).print(output_stream, /*isSigned=*/false);
  1093. output_stream << "`";
  1094. break;
  1095. case TokenKind::RealLiteral:
  1096. output_stream << ", value: `" << GetRealLiteral(token) << "`";
  1097. break;
  1098. case TokenKind::StringLiteral:
  1099. output_stream << ", value: `" << GetStringLiteral(token) << "`";
  1100. break;
  1101. default:
  1102. if (token_info.kind.is_opening_symbol()) {
  1103. output_stream << ", closing_token: "
  1104. << GetMatchedClosingToken(token).index;
  1105. } else if (token_info.kind.is_closing_symbol()) {
  1106. output_stream << ", opening_token: "
  1107. << GetMatchedOpeningToken(token).index;
  1108. }
  1109. break;
  1110. }
  1111. if (token_info.has_trailing_space) {
  1112. output_stream << ", has_trailing_space: true";
  1113. }
  1114. if (token_info.is_recovery) {
  1115. output_stream << ", recovery: true";
  1116. }
  1117. output_stream << " },";
  1118. }
  1119. auto TokenizedBuffer::GetLineInfo(Line line) -> LineInfo& {
  1120. return line_infos_[line.index];
  1121. }
  1122. auto TokenizedBuffer::GetLineInfo(Line line) const -> const LineInfo& {
  1123. return line_infos_[line.index];
  1124. }
  1125. auto TokenizedBuffer::AddLine(LineInfo info) -> Line {
  1126. line_infos_.push_back(info);
  1127. return Line(static_cast<int>(line_infos_.size()) - 1);
  1128. }
  1129. auto TokenizedBuffer::GetTokenInfo(Token token) -> TokenInfo& {
  1130. return token_infos_[token.index];
  1131. }
  1132. auto TokenizedBuffer::GetTokenInfo(Token token) const -> const TokenInfo& {
  1133. return token_infos_[token.index];
  1134. }
  1135. auto TokenizedBuffer::AddToken(TokenInfo info) -> Token {
  1136. token_infos_.push_back(info);
  1137. expected_parse_tree_size_ += info.kind.expected_parse_tree_size();
  1138. return Token(static_cast<int>(token_infos_.size()) - 1);
  1139. }
  1140. auto TokenIterator::Print(llvm::raw_ostream& output) const -> void {
  1141. output << token_.index;
  1142. }
  1143. auto TokenizedBuffer::SourceBufferLocationTranslator::GetLocation(
  1144. const char* loc) -> DiagnosticLocation {
  1145. CARBON_CHECK(StringRefContainsPointer(buffer_->source_->text(), loc))
  1146. << "location not within buffer";
  1147. int64_t offset = loc - buffer_->source_->text().begin();
  1148. // Find the first line starting after the given location. Note that we can't
  1149. // inspect `line.length` here because it is not necessarily correct for the
  1150. // final line during lexing (but will be correct later for the parse tree).
  1151. const auto* line_it = std::partition_point(
  1152. buffer_->line_infos_.begin(), buffer_->line_infos_.end(),
  1153. [offset](const LineInfo& line) { return line.start <= offset; });
  1154. // Step back one line to find the line containing the given position.
  1155. CARBON_CHECK(line_it != buffer_->line_infos_.begin())
  1156. << "location precedes the start of the first line";
  1157. --line_it;
  1158. int line_number = line_it - buffer_->line_infos_.begin();
  1159. int column_number = offset - line_it->start;
  1160. // Start by grabbing the line from the buffer. If the line isn't fully lexed,
  1161. // the length will be npos and the line will be grabbed from the known start
  1162. // to the end of the buffer; we'll then adjust the length.
  1163. llvm::StringRef line =
  1164. buffer_->source_->text().substr(line_it->start, line_it->length);
  1165. if (line_it->length == static_cast<int32_t>(llvm::StringRef::npos)) {
  1166. CARBON_CHECK(line.take_front(column_number).count('\n') == 0)
  1167. << "Currently we assume no unlexed newlines prior to the error column, "
  1168. "but there was one when erroring at "
  1169. << buffer_->source_->filename() << ":" << line_number << ":"
  1170. << column_number;
  1171. // Look for the next newline since we don't know the length. We can start at
  1172. // the column because prior newlines will have been lexed.
  1173. auto end_newline_pos = line.find('\n', column_number);
  1174. if (end_newline_pos != llvm::StringRef::npos) {
  1175. line = line.take_front(end_newline_pos);
  1176. }
  1177. }
  1178. return {.file_name = buffer_->source_->filename(),
  1179. .line = line,
  1180. .line_number = line_number + 1,
  1181. .column_number = column_number + 1};
  1182. }
  1183. auto TokenLocationTranslator::GetLocation(Token token) -> DiagnosticLocation {
  1184. // Map the token location into a position within the source buffer.
  1185. const auto& token_info = buffer_->GetTokenInfo(token);
  1186. const auto& line_info = buffer_->GetLineInfo(token_info.token_line);
  1187. const char* token_start =
  1188. buffer_->source_->text().begin() + line_info.start + token_info.column;
  1189. // Find the corresponding file location.
  1190. // TODO: Should we somehow indicate in the diagnostic location if this token
  1191. // is a recovery token that doesn't correspond to the original source?
  1192. return TokenizedBuffer::SourceBufferLocationTranslator(buffer_).GetLocation(
  1193. token_start);
  1194. }
  1195. } // namespace Carbon::Lex