tokenized_buffer.cpp 45 KB

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