tokenized_buffer.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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 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. using DispatchFunctionT = auto(Lexer& lexer, llvm::StringRef& source_text)
  223. -> LexResult;
  224. using DispatchTableT = std::array<DispatchFunctionT*, 256>;
  225. Lexer(TokenizedBuffer& buffer, DiagnosticConsumer& consumer)
  226. : buffer_(&buffer),
  227. translator_(&buffer),
  228. emitter_(translator_, consumer),
  229. token_translator_(&buffer),
  230. token_emitter_(token_translator_, consumer),
  231. current_line_(buffer.AddLine(LineInfo(0))),
  232. current_line_info_(&buffer.GetLineInfo(current_line_)) {}
  233. // Perform the necessary bookkeeping to step past a newline at the current
  234. // line and column.
  235. auto HandleNewline() -> void {
  236. current_line_info_->length = current_column_;
  237. current_line_ = buffer_->AddLine(
  238. LineInfo(current_line_info_->start + current_column_ + 1));
  239. current_line_info_ = &buffer_->GetLineInfo(current_line_);
  240. current_column_ = 0;
  241. set_indent_ = false;
  242. }
  243. auto NoteWhitespace() -> void {
  244. if (!buffer_->token_infos_.empty()) {
  245. buffer_->token_infos_.back().has_trailing_space = true;
  246. }
  247. }
  248. auto SkipWhitespace(llvm::StringRef& source_text) -> bool {
  249. const char* const whitespace_start = source_text.begin();
  250. while (!source_text.empty()) {
  251. // We only support line-oriented commenting and lex comments as-if they
  252. // were whitespace.
  253. if (source_text.startswith("//")) {
  254. // Any comment must be the only non-whitespace on the line.
  255. if (set_indent_) {
  256. CARBON_DIAGNOSTIC(TrailingComment, Error,
  257. "Trailing comments are not permitted.");
  258. emitter_.Emit(source_text.begin(), TrailingComment);
  259. }
  260. // The introducer '//' must be followed by whitespace or EOF.
  261. if (source_text.size() > 2 && !IsSpace(source_text[2])) {
  262. CARBON_DIAGNOSTIC(NoWhitespaceAfterCommentIntroducer, Error,
  263. "Whitespace is required after '//'.");
  264. emitter_.Emit(source_text.begin() + 2,
  265. NoWhitespaceAfterCommentIntroducer);
  266. }
  267. while (!source_text.empty() && source_text.front() != '\n') {
  268. ++current_column_;
  269. source_text = source_text.drop_front();
  270. }
  271. if (source_text.empty()) {
  272. break;
  273. }
  274. }
  275. switch (source_text.front()) {
  276. default:
  277. // If we find a non-whitespace character without exhausting the
  278. // buffer, return true to continue lexing.
  279. CARBON_CHECK(!IsSpace(source_text.front()));
  280. if (whitespace_start != source_text.begin()) {
  281. NoteWhitespace();
  282. }
  283. return true;
  284. case '\n':
  285. // If this is the last character in the source, directly return here
  286. // to avoid creating an empty line.
  287. source_text = source_text.drop_front();
  288. if (source_text.empty()) {
  289. current_line_info_->length = current_column_;
  290. return false;
  291. }
  292. // Otherwise, add a line and set up to continue lexing.
  293. HandleNewline();
  294. continue;
  295. case ' ':
  296. case '\t':
  297. // Skip other forms of whitespace while tracking column.
  298. // TODO: This obviously needs looooots more work to handle unicode
  299. // whitespace as well as special handling to allow better tokenization
  300. // of operators. This is just a stub to check that our column
  301. // management works.
  302. ++current_column_;
  303. source_text = source_text.drop_front();
  304. continue;
  305. }
  306. }
  307. CARBON_CHECK(source_text.empty())
  308. << "Cannot reach here w/o finishing the text!";
  309. // Update the line length as this is also the end of a line.
  310. current_line_info_->length = current_column_;
  311. return false;
  312. }
  313. auto LexNumericLiteral(llvm::StringRef& source_text) -> LexResult {
  314. std::optional<NumericLiteral> literal = NumericLiteral::Lex(source_text);
  315. if (!literal) {
  316. return LexError(source_text);
  317. }
  318. int int_column = current_column_;
  319. int token_size = literal->text().size();
  320. current_column_ += token_size;
  321. source_text = source_text.drop_front(token_size);
  322. if (!set_indent_) {
  323. current_line_info_->indent = int_column;
  324. set_indent_ = true;
  325. }
  326. return VariantMatch(
  327. literal->ComputeValue(emitter_),
  328. [&](NumericLiteral::IntegerValue&& value) {
  329. auto token = buffer_->AddToken({.kind = TokenKind::IntegerLiteral,
  330. .token_line = current_line_,
  331. .column = int_column});
  332. buffer_->GetTokenInfo(token).literal_index =
  333. buffer_->literal_int_storage_.size();
  334. buffer_->literal_int_storage_.push_back(std::move(value.value));
  335. return token;
  336. },
  337. [&](NumericLiteral::RealValue&& value) {
  338. auto token = buffer_->AddToken({.kind = TokenKind::RealLiteral,
  339. .token_line = current_line_,
  340. .column = int_column});
  341. buffer_->GetTokenInfo(token).literal_index =
  342. buffer_->literal_int_storage_.size();
  343. buffer_->literal_int_storage_.push_back(std::move(value.mantissa));
  344. buffer_->literal_int_storage_.push_back(std::move(value.exponent));
  345. CARBON_CHECK(buffer_->GetRealLiteral(token).is_decimal ==
  346. (value.radix == NumericLiteral::Radix::Decimal));
  347. return token;
  348. },
  349. [&](NumericLiteral::UnrecoverableError) {
  350. auto token = buffer_->AddToken({
  351. .kind = TokenKind::Error,
  352. .token_line = current_line_,
  353. .column = int_column,
  354. .error_length = token_size,
  355. });
  356. return token;
  357. });
  358. }
  359. auto LexStringLiteral(llvm::StringRef& source_text) -> LexResult {
  360. std::optional<StringLiteral> literal = StringLiteral::Lex(source_text);
  361. if (!literal) {
  362. return LexError(source_text);
  363. }
  364. Line string_line = current_line_;
  365. int string_column = current_column_;
  366. int literal_size = literal->text().size();
  367. source_text = source_text.drop_front(literal_size);
  368. if (!set_indent_) {
  369. current_line_info_->indent = string_column;
  370. set_indent_ = true;
  371. }
  372. // Update line and column information.
  373. if (!literal->is_multi_line()) {
  374. current_column_ += literal_size;
  375. } else {
  376. for (char c : literal->text()) {
  377. if (c == '\n') {
  378. HandleNewline();
  379. // The indentation of all lines in a multi-line string literal is
  380. // that of the first line.
  381. current_line_info_->indent = string_column;
  382. set_indent_ = true;
  383. } else {
  384. ++current_column_;
  385. }
  386. }
  387. }
  388. if (literal->is_terminated()) {
  389. auto token =
  390. buffer_->AddToken({.kind = TokenKind::StringLiteral,
  391. .token_line = string_line,
  392. .column = string_column,
  393. .literal_index = static_cast<int32_t>(
  394. buffer_->literal_string_storage_.size())});
  395. buffer_->literal_string_storage_.push_back(
  396. literal->ComputeValue(emitter_));
  397. return token;
  398. } else {
  399. CARBON_DIAGNOSTIC(UnterminatedString, Error,
  400. "String is missing a terminator.");
  401. emitter_.Emit(literal->text().begin(), UnterminatedString);
  402. return buffer_->AddToken({.kind = TokenKind::Error,
  403. .token_line = string_line,
  404. .column = string_column,
  405. .error_length = literal_size});
  406. }
  407. }
  408. auto LexSymbolToken(llvm::StringRef& source_text,
  409. TokenKind kind = TokenKind::Error) -> LexResult {
  410. auto compute_symbol_kind = [](llvm::StringRef source_text) {
  411. return llvm::StringSwitch<TokenKind>(source_text)
  412. #define CARBON_SYMBOL_TOKEN(Name, Spelling) \
  413. .StartsWith(Spelling, TokenKind::Name)
  414. #include "toolchain/lex/token_kind.def"
  415. .Default(TokenKind::Error);
  416. };
  417. // We use the `error` token as a place-holder for cases where one character
  418. // isn't enough to pick a definitive symbol token. Recompute the kind using
  419. // the full symbol set.
  420. if (LLVM_UNLIKELY(kind == TokenKind::Error)) {
  421. kind = compute_symbol_kind(source_text);
  422. if (kind == TokenKind::Error) {
  423. return LexError(source_text);
  424. }
  425. } else {
  426. // Verify in a debug build that the incoming token kind is correct.
  427. CARBON_DCHECK(kind == compute_symbol_kind(source_text))
  428. << "Incoming token kind '" << kind
  429. << "' does not match computed kind '"
  430. << compute_symbol_kind(source_text) << "'!";
  431. }
  432. if (!set_indent_) {
  433. current_line_info_->indent = current_column_;
  434. set_indent_ = true;
  435. }
  436. CloseInvalidOpenGroups(kind);
  437. const char* location = source_text.begin();
  438. Token token = buffer_->AddToken(
  439. {.kind = kind, .token_line = current_line_, .column = current_column_});
  440. current_column_ += kind.fixed_spelling().size();
  441. source_text = source_text.drop_front(kind.fixed_spelling().size());
  442. // Opening symbols just need to be pushed onto our queue of opening groups.
  443. if (kind.is_opening_symbol()) {
  444. open_groups_.push_back(token);
  445. return token;
  446. }
  447. // Only closing symbols need further special handling.
  448. if (!kind.is_closing_symbol()) {
  449. return token;
  450. }
  451. TokenInfo& closing_token_info = buffer_->GetTokenInfo(token);
  452. // Check that there is a matching opening symbol before we consume this as
  453. // a closing symbol.
  454. if (open_groups_.empty()) {
  455. closing_token_info.kind = TokenKind::Error;
  456. closing_token_info.error_length = kind.fixed_spelling().size();
  457. CARBON_DIAGNOSTIC(
  458. UnmatchedClosing, Error,
  459. "Closing symbol without a corresponding opening symbol.");
  460. emitter_.Emit(location, UnmatchedClosing);
  461. // Note that this still returns true as we do consume a symbol.
  462. return token;
  463. }
  464. // Finally can handle a normal closing symbol.
  465. Token opening_token = open_groups_.pop_back_val();
  466. TokenInfo& opening_token_info = buffer_->GetTokenInfo(opening_token);
  467. opening_token_info.closing_token = token;
  468. closing_token_info.opening_token = opening_token;
  469. return token;
  470. }
  471. // Given a word that has already been lexed, determine whether it is a type
  472. // literal and if so form the corresponding token.
  473. auto LexWordAsTypeLiteralToken(llvm::StringRef word, int column)
  474. -> LexResult {
  475. if (word.size() < 2) {
  476. // Too short to form one of these tokens.
  477. return LexResult::NoMatch();
  478. }
  479. if (word[1] < '1' || word[1] > '9') {
  480. // Doesn't start with a valid initial digit.
  481. return LexResult::NoMatch();
  482. }
  483. std::optional<TokenKind> kind;
  484. switch (word.front()) {
  485. case 'i':
  486. kind = TokenKind::IntegerTypeLiteral;
  487. break;
  488. case 'u':
  489. kind = TokenKind::UnsignedIntegerTypeLiteral;
  490. break;
  491. case 'f':
  492. kind = TokenKind::FloatingPointTypeLiteral;
  493. break;
  494. default:
  495. return LexResult::NoMatch();
  496. };
  497. llvm::StringRef suffix = word.substr(1);
  498. if (!CanLexInteger(emitter_, suffix)) {
  499. return buffer_->AddToken(
  500. {.kind = TokenKind::Error,
  501. .token_line = current_line_,
  502. .column = column,
  503. .error_length = static_cast<int32_t>(word.size())});
  504. }
  505. llvm::APInt suffix_value;
  506. if (suffix.getAsInteger(10, suffix_value)) {
  507. return LexResult::NoMatch();
  508. }
  509. auto token = buffer_->AddToken(
  510. {.kind = *kind, .token_line = current_line_, .column = column});
  511. buffer_->GetTokenInfo(token).literal_index =
  512. buffer_->literal_int_storage_.size();
  513. buffer_->literal_int_storage_.push_back(std::move(suffix_value));
  514. return token;
  515. }
  516. // Closes all open groups that cannot remain open across the symbol `K`.
  517. // Users may pass `Error` to close all open groups.
  518. auto CloseInvalidOpenGroups(TokenKind kind) -> void {
  519. if (!kind.is_closing_symbol() && kind != TokenKind::Error) {
  520. return;
  521. }
  522. while (!open_groups_.empty()) {
  523. Token opening_token = open_groups_.back();
  524. TokenKind opening_kind = buffer_->GetTokenInfo(opening_token).kind;
  525. if (kind == opening_kind.closing_symbol()) {
  526. return;
  527. }
  528. open_groups_.pop_back();
  529. CARBON_DIAGNOSTIC(
  530. MismatchedClosing, Error,
  531. "Closing symbol does not match most recent opening symbol.");
  532. token_emitter_.Emit(opening_token, MismatchedClosing);
  533. CARBON_CHECK(!buffer_->tokens().empty())
  534. << "Must have a prior opening token!";
  535. Token prev_token = buffer_->tokens().end()[-1];
  536. // TODO: do a smarter backwards scan for where to put the closing
  537. // token.
  538. Token closing_token = buffer_->AddToken(
  539. {.kind = opening_kind.closing_symbol(),
  540. .has_trailing_space = buffer_->HasTrailingWhitespace(prev_token),
  541. .is_recovery = true,
  542. .token_line = current_line_,
  543. .column = current_column_});
  544. TokenInfo& opening_token_info = buffer_->GetTokenInfo(opening_token);
  545. TokenInfo& closing_token_info = buffer_->GetTokenInfo(closing_token);
  546. opening_token_info.closing_token = closing_token;
  547. closing_token_info.opening_token = opening_token;
  548. }
  549. }
  550. auto GetOrCreateIdentifier(llvm::StringRef text) -> Identifier {
  551. auto insert_result = buffer_->identifier_map_.insert(
  552. {text, Identifier(buffer_->identifier_infos_.size())});
  553. if (insert_result.second) {
  554. buffer_->identifier_infos_.push_back({text});
  555. }
  556. return insert_result.first->second;
  557. }
  558. auto LexKeywordOrIdentifier(llvm::StringRef& source_text) -> LexResult {
  559. if (static_cast<unsigned char>(source_text.front()) > 0x7F) {
  560. // TODO: Need to add support for Unicode lexing.
  561. return LexError(source_text);
  562. }
  563. CARBON_CHECK(IsAlpha(source_text.front()) || source_text.front() == '_');
  564. if (!set_indent_) {
  565. current_line_info_->indent = current_column_;
  566. set_indent_ = true;
  567. }
  568. // Take the valid characters off the front of the source buffer.
  569. llvm::StringRef identifier_text = ScanForIdentifierPrefix(source_text);
  570. CARBON_CHECK(!identifier_text.empty())
  571. << "Must have at least one character!";
  572. int identifier_column = current_column_;
  573. current_column_ += identifier_text.size();
  574. source_text = source_text.drop_front(identifier_text.size());
  575. // Check if the text is a type literal, and if so form such a literal.
  576. if (LexResult result =
  577. LexWordAsTypeLiteralToken(identifier_text, identifier_column)) {
  578. return result;
  579. }
  580. // Check if the text matches a keyword token, and if so use that.
  581. TokenKind kind = llvm::StringSwitch<TokenKind>(identifier_text)
  582. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, TokenKind::Name)
  583. #include "toolchain/lex/token_kind.def"
  584. .Default(TokenKind::Error);
  585. if (kind != TokenKind::Error) {
  586. return buffer_->AddToken({.kind = kind,
  587. .token_line = current_line_,
  588. .column = identifier_column});
  589. }
  590. // Otherwise we have a generic identifier.
  591. return buffer_->AddToken({.kind = TokenKind::Identifier,
  592. .token_line = current_line_,
  593. .column = identifier_column,
  594. .id = GetOrCreateIdentifier(identifier_text)});
  595. }
  596. auto LexError(llvm::StringRef& source_text) -> LexResult {
  597. llvm::StringRef error_text = source_text.take_while([](char c) {
  598. if (IsAlnum(c)) {
  599. return false;
  600. }
  601. switch (c) {
  602. case '_':
  603. case '\t':
  604. case '\n':
  605. return false;
  606. default:
  607. break;
  608. }
  609. return llvm::StringSwitch<bool>(llvm::StringRef(&c, 1))
  610. #define CARBON_SYMBOL_TOKEN(Name, Spelling) .StartsWith(Spelling, false)
  611. #include "toolchain/lex/token_kind.def"
  612. .Default(true);
  613. });
  614. if (error_text.empty()) {
  615. // TODO: Reimplement this to use the lexer properly. In the meantime,
  616. // guarantee that we eat at least one byte.
  617. error_text = source_text.take_front(1);
  618. }
  619. auto token = buffer_->AddToken(
  620. {.kind = TokenKind::Error,
  621. .token_line = current_line_,
  622. .column = current_column_,
  623. .error_length = static_cast<int32_t>(error_text.size())});
  624. CARBON_DIAGNOSTIC(UnrecognizedCharacters, Error,
  625. "Encountered unrecognized characters while parsing.");
  626. emitter_.Emit(error_text.begin(), UnrecognizedCharacters);
  627. current_column_ += error_text.size();
  628. source_text = source_text.drop_front(error_text.size());
  629. return token;
  630. }
  631. auto AddEndOfFileToken() -> void {
  632. buffer_->AddToken({.kind = TokenKind::EndOfFile,
  633. .token_line = current_line_,
  634. .column = current_column_});
  635. }
  636. constexpr static auto MakeDispatchTable() -> DispatchTableT {
  637. DispatchTableT table = {};
  638. auto dispatch_lex_error = +[](Lexer& lexer, llvm::StringRef& source_text) {
  639. return lexer.LexError(source_text);
  640. };
  641. for (int i = 0; i < 256; ++i) {
  642. table[i] = dispatch_lex_error;
  643. }
  644. // Symbols have some special dispatching. First, set the first character of
  645. // each symbol token spelling to dispatch to the symbol lexer. We don't
  646. // provide a pre-computed token here, so the symbol lexer will compute the
  647. // exact symbol token kind.
  648. auto dispatch_lex_symbol = +[](Lexer& lexer, llvm::StringRef& source_text) {
  649. return lexer.LexSymbolToken(source_text);
  650. };
  651. #define CARBON_SYMBOL_TOKEN(TokenName, Spelling) \
  652. table[(Spelling)[0]] = dispatch_lex_symbol;
  653. #include "toolchain/lex/token_kind.def"
  654. // Now special cased single-character symbols that are guaranteed to not
  655. // join with another symbol. These are grouping symbols, terminators,
  656. // or separators in the grammar and have a good reason to be
  657. // orthogonal to any other punctuation. We do this separately because this
  658. // needs to override some of the generic handling above, and provide a
  659. // custom token.
  660. #define CARBON_ONE_CHAR_SYMBOL_TOKEN(TokenName, Spelling) \
  661. table[(Spelling)[0]] = +[](Lexer& lexer, llvm::StringRef& source_text) { \
  662. return lexer.LexSymbolToken(source_text, TokenKind::TokenName); \
  663. };
  664. #include "toolchain/lex/token_kind.def"
  665. auto dispatch_lex_word = +[](Lexer& lexer, llvm::StringRef& source_text) {
  666. return lexer.LexKeywordOrIdentifier(source_text);
  667. };
  668. table['_'] = dispatch_lex_word;
  669. // Note that we don't use `llvm::seq` because this needs to be `constexpr`
  670. // evaluated.
  671. for (unsigned char c = 'a'; c <= 'z'; ++c) {
  672. table[c] = dispatch_lex_word;
  673. }
  674. for (unsigned char c = 'A'; c <= 'Z'; ++c) {
  675. table[c] = dispatch_lex_word;
  676. }
  677. // We dispatch all non-ASCII UTF-8 characters to the identifier lexing
  678. // as whitespace characters should already have been skipped and the
  679. // only remaining valid Unicode characters would be part of an
  680. // identifier. That code can either accept or reject.
  681. for (int i = 0x80; i < 0x100; ++i) {
  682. table[i] = dispatch_lex_word;
  683. }
  684. auto dispatch_lex_numeric =
  685. +[](Lexer& lexer, llvm::StringRef& source_text) {
  686. return lexer.LexNumericLiteral(source_text);
  687. };
  688. for (unsigned char c = '0'; c <= '9'; ++c) {
  689. table[c] = dispatch_lex_numeric;
  690. }
  691. auto dispatch_lex_string = +[](Lexer& lexer, llvm::StringRef& source_text) {
  692. return lexer.LexStringLiteral(source_text);
  693. };
  694. table['\''] = dispatch_lex_string;
  695. table['"'] = dispatch_lex_string;
  696. table['#'] = dispatch_lex_string;
  697. return table;
  698. };
  699. private:
  700. TokenizedBuffer* buffer_;
  701. SourceBufferLocationTranslator translator_;
  702. LexerDiagnosticEmitter emitter_;
  703. TokenLocationTranslator token_translator_;
  704. TokenDiagnosticEmitter token_emitter_;
  705. Line current_line_;
  706. LineInfo* current_line_info_;
  707. int current_column_ = 0;
  708. bool set_indent_ = false;
  709. llvm::SmallVector<Token> open_groups_;
  710. };
  711. auto TokenizedBuffer::Lex(SourceBuffer& source, DiagnosticConsumer& consumer)
  712. -> TokenizedBuffer {
  713. TokenizedBuffer buffer(source);
  714. ErrorTrackingDiagnosticConsumer error_tracking_consumer(consumer);
  715. Lexer lexer(buffer, error_tracking_consumer);
  716. // Build a table of function pointers that we can use to dispatch to the
  717. // correct lexer routine based on the first byte of source text.
  718. //
  719. // While it is tempting to simply use a `switch` on the first byte and
  720. // dispatch with cases into this, in practice that doesn't produce great code.
  721. // There seem to be two issues that are the root cause.
  722. //
  723. // First, there are lots of different values of bytes that dispatch to a
  724. // fairly small set of routines, and then some byte values that dispatch
  725. // differently for each byte. This pattern isn't one that the compiler-based
  726. // lowering of switches works well with -- it tries to balance all the cases,
  727. // and in doing so emits several compares and other control flow rather than a
  728. // simple jump table.
  729. //
  730. // Second, with a `case`, it isn't as obvious how to create a single, uniform
  731. // interface that is effective for *every* byte value, and thus makes for a
  732. // single consistent table-based dispatch. By forcing these to be function
  733. // pointers, we also coerce the code to use a strictly homogeneous structure
  734. // that can form a single dispatch table.
  735. //
  736. // These two actually interact -- the second issue is part of what makes the
  737. // non-table lowering in the first one desirable for many switches and cases.
  738. //
  739. // Ultimately, when table-based dispatch is such an important technique, we
  740. // get better results by taking full control and manually creating the
  741. // dispatch structures.
  742. constexpr Lexer::DispatchTableT DispatchTable = Lexer::MakeDispatchTable();
  743. llvm::StringRef source_text = source.text();
  744. while (lexer.SkipWhitespace(source_text)) {
  745. Lexer::LexResult result =
  746. DispatchTable[static_cast<unsigned char>(source_text.front())](
  747. lexer, source_text);
  748. CARBON_CHECK(result) << "Failed to form a token!";
  749. }
  750. // The end-of-file token is always considered to be whitespace.
  751. lexer.NoteWhitespace();
  752. lexer.CloseInvalidOpenGroups(TokenKind::Error);
  753. lexer.AddEndOfFileToken();
  754. if (error_tracking_consumer.seen_error()) {
  755. buffer.has_errors_ = true;
  756. }
  757. return buffer;
  758. }
  759. auto TokenizedBuffer::GetKind(Token token) const -> TokenKind {
  760. return GetTokenInfo(token).kind;
  761. }
  762. auto TokenizedBuffer::GetLine(Token token) const -> Line {
  763. return GetTokenInfo(token).token_line;
  764. }
  765. auto TokenizedBuffer::GetLineNumber(Token token) const -> int {
  766. return GetLineNumber(GetLine(token));
  767. }
  768. auto TokenizedBuffer::GetColumnNumber(Token token) const -> int {
  769. return GetTokenInfo(token).column + 1;
  770. }
  771. auto TokenizedBuffer::GetTokenText(Token token) const -> llvm::StringRef {
  772. const auto& token_info = GetTokenInfo(token);
  773. llvm::StringRef fixed_spelling = token_info.kind.fixed_spelling();
  774. if (!fixed_spelling.empty()) {
  775. return fixed_spelling;
  776. }
  777. if (token_info.kind == TokenKind::Error) {
  778. const auto& line_info = GetLineInfo(token_info.token_line);
  779. int64_t token_start = line_info.start + token_info.column;
  780. return source_->text().substr(token_start, token_info.error_length);
  781. }
  782. // Refer back to the source text to preserve oddities like radix or digit
  783. // separators the author included.
  784. if (token_info.kind == TokenKind::IntegerLiteral ||
  785. token_info.kind == TokenKind::RealLiteral) {
  786. const auto& line_info = GetLineInfo(token_info.token_line);
  787. int64_t token_start = line_info.start + token_info.column;
  788. std::optional<NumericLiteral> relexed_token =
  789. NumericLiteral::Lex(source_->text().substr(token_start));
  790. CARBON_CHECK(relexed_token) << "Could not reform numeric literal token.";
  791. return relexed_token->text();
  792. }
  793. // Refer back to the source text to find the original spelling, including
  794. // escape sequences etc.
  795. if (token_info.kind == TokenKind::StringLiteral) {
  796. const auto& line_info = GetLineInfo(token_info.token_line);
  797. int64_t token_start = line_info.start + token_info.column;
  798. std::optional<StringLiteral> relexed_token =
  799. StringLiteral::Lex(source_->text().substr(token_start));
  800. CARBON_CHECK(relexed_token) << "Could not reform string literal token.";
  801. return relexed_token->text();
  802. }
  803. // Refer back to the source text to avoid needing to reconstruct the
  804. // spelling from the size.
  805. if (token_info.kind.is_sized_type_literal()) {
  806. const auto& line_info = GetLineInfo(token_info.token_line);
  807. int64_t token_start = line_info.start + token_info.column;
  808. llvm::StringRef suffix =
  809. source_->text().substr(token_start + 1).take_while(IsDecimalDigit);
  810. return llvm::StringRef(suffix.data() - 1, suffix.size() + 1);
  811. }
  812. if (token_info.kind == TokenKind::EndOfFile) {
  813. return llvm::StringRef();
  814. }
  815. CARBON_CHECK(token_info.kind == TokenKind::Identifier) << token_info.kind;
  816. return GetIdentifierText(token_info.id);
  817. }
  818. auto TokenizedBuffer::GetIdentifier(Token token) const -> Identifier {
  819. const auto& token_info = GetTokenInfo(token);
  820. CARBON_CHECK(token_info.kind == TokenKind::Identifier) << token_info.kind;
  821. return token_info.id;
  822. }
  823. auto TokenizedBuffer::GetIntegerLiteral(Token token) const
  824. -> const llvm::APInt& {
  825. const auto& token_info = GetTokenInfo(token);
  826. CARBON_CHECK(token_info.kind == TokenKind::IntegerLiteral) << token_info.kind;
  827. return literal_int_storage_[token_info.literal_index];
  828. }
  829. auto TokenizedBuffer::GetRealLiteral(Token token) const -> RealLiteralValue {
  830. const auto& token_info = GetTokenInfo(token);
  831. CARBON_CHECK(token_info.kind == TokenKind::RealLiteral) << token_info.kind;
  832. // Note that every real literal is at least three characters long, so we can
  833. // safely look at the second character to determine whether we have a
  834. // decimal or hexadecimal literal.
  835. const auto& line_info = GetLineInfo(token_info.token_line);
  836. int64_t token_start = line_info.start + token_info.column;
  837. char second_char = source_->text()[token_start + 1];
  838. bool is_decimal = second_char != 'x' && second_char != 'b';
  839. return {.mantissa = literal_int_storage_[token_info.literal_index],
  840. .exponent = literal_int_storage_[token_info.literal_index + 1],
  841. .is_decimal = is_decimal};
  842. }
  843. auto TokenizedBuffer::GetStringLiteral(Token token) const -> llvm::StringRef {
  844. const auto& token_info = GetTokenInfo(token);
  845. CARBON_CHECK(token_info.kind == TokenKind::StringLiteral) << token_info.kind;
  846. return literal_string_storage_[token_info.literal_index];
  847. }
  848. auto TokenizedBuffer::GetTypeLiteralSize(Token token) const
  849. -> const llvm::APInt& {
  850. const auto& token_info = GetTokenInfo(token);
  851. CARBON_CHECK(token_info.kind.is_sized_type_literal()) << token_info.kind;
  852. return literal_int_storage_[token_info.literal_index];
  853. }
  854. auto TokenizedBuffer::GetMatchedClosingToken(Token opening_token) const
  855. -> Token {
  856. const auto& opening_token_info = GetTokenInfo(opening_token);
  857. CARBON_CHECK(opening_token_info.kind.is_opening_symbol())
  858. << opening_token_info.kind;
  859. return opening_token_info.closing_token;
  860. }
  861. auto TokenizedBuffer::GetMatchedOpeningToken(Token closing_token) const
  862. -> Token {
  863. const auto& closing_token_info = GetTokenInfo(closing_token);
  864. CARBON_CHECK(closing_token_info.kind.is_closing_symbol())
  865. << closing_token_info.kind;
  866. return closing_token_info.opening_token;
  867. }
  868. auto TokenizedBuffer::HasLeadingWhitespace(Token token) const -> bool {
  869. auto it = TokenIterator(token);
  870. return it == tokens().begin() || GetTokenInfo(*(it - 1)).has_trailing_space;
  871. }
  872. auto TokenizedBuffer::HasTrailingWhitespace(Token token) const -> bool {
  873. return GetTokenInfo(token).has_trailing_space;
  874. }
  875. auto TokenizedBuffer::IsRecoveryToken(Token token) const -> bool {
  876. return GetTokenInfo(token).is_recovery;
  877. }
  878. auto TokenizedBuffer::GetLineNumber(Line line) const -> int {
  879. return line.index + 1;
  880. }
  881. auto TokenizedBuffer::GetIndentColumnNumber(Line line) const -> int {
  882. return GetLineInfo(line).indent + 1;
  883. }
  884. auto TokenizedBuffer::GetIdentifierText(Identifier identifier) const
  885. -> llvm::StringRef {
  886. return identifier_infos_[identifier.index].text;
  887. }
  888. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  889. index = std::max(widths.index, index);
  890. kind = std::max(widths.kind, kind);
  891. column = std::max(widths.column, column);
  892. line = std::max(widths.line, line);
  893. indent = std::max(widths.indent, indent);
  894. }
  895. // Compute the printed width of a number. When numbers are printed in decimal,
  896. // the number of digits needed is is one more than the log-base-10 of the
  897. // value. We handle a value of `zero` explicitly.
  898. //
  899. // This routine requires its argument to be *non-negative*.
  900. static auto ComputeDecimalPrintedWidth(int number) -> int {
  901. CARBON_CHECK(number >= 0) << "Negative numbers are not supported.";
  902. if (number == 0) {
  903. return 1;
  904. }
  905. return static_cast<int>(std::log10(number)) + 1;
  906. }
  907. auto TokenizedBuffer::GetTokenPrintWidths(Token token) const -> PrintWidths {
  908. PrintWidths widths = {};
  909. widths.index = ComputeDecimalPrintedWidth(token_infos_.size());
  910. widths.kind = GetKind(token).name().size();
  911. widths.line = ComputeDecimalPrintedWidth(GetLineNumber(token));
  912. widths.column = ComputeDecimalPrintedWidth(GetColumnNumber(token));
  913. widths.indent =
  914. ComputeDecimalPrintedWidth(GetIndentColumnNumber(GetLine(token)));
  915. return widths;
  916. }
  917. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  918. if (tokens().begin() == tokens().end()) {
  919. return;
  920. }
  921. output_stream << "- filename: " << source_->filename() << "\n"
  922. << " tokens: [\n";
  923. PrintWidths widths = {};
  924. widths.index = ComputeDecimalPrintedWidth((token_infos_.size()));
  925. for (Token token : tokens()) {
  926. widths.Widen(GetTokenPrintWidths(token));
  927. }
  928. for (Token token : tokens()) {
  929. PrintToken(output_stream, token, widths);
  930. output_stream << "\n";
  931. }
  932. output_stream << " ]\n";
  933. }
  934. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  935. Token token) const -> void {
  936. PrintToken(output_stream, token, {});
  937. }
  938. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, Token token,
  939. PrintWidths widths) const -> void {
  940. widths.Widen(GetTokenPrintWidths(token));
  941. int token_index = token.index;
  942. const auto& token_info = GetTokenInfo(token);
  943. llvm::StringRef token_text = GetTokenText(token);
  944. // Output the main chunk using one format string. We have to do the
  945. // justification manually in order to use the dynamically computed widths
  946. // and get the quotes included.
  947. output_stream << llvm::formatv(
  948. " { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  949. "spelling: '{5}'",
  950. llvm::format_decimal(token_index, widths.index),
  951. llvm::right_justify(llvm::formatv("'{0}'", token_info.kind.name()).str(),
  952. widths.kind + 2),
  953. llvm::format_decimal(GetLineNumber(token_info.token_line), widths.line),
  954. llvm::format_decimal(GetColumnNumber(token), widths.column),
  955. llvm::format_decimal(GetIndentColumnNumber(token_info.token_line),
  956. widths.indent),
  957. token_text);
  958. switch (token_info.kind) {
  959. case TokenKind::Identifier:
  960. output_stream << ", identifier: " << GetIdentifier(token).index;
  961. break;
  962. case TokenKind::IntegerLiteral:
  963. output_stream << ", value: `";
  964. GetIntegerLiteral(token).print(output_stream, /*isSigned=*/false);
  965. output_stream << "`";
  966. break;
  967. case TokenKind::RealLiteral:
  968. output_stream << ", value: `" << GetRealLiteral(token) << "`";
  969. break;
  970. case TokenKind::StringLiteral:
  971. output_stream << ", value: `" << GetStringLiteral(token) << "`";
  972. break;
  973. default:
  974. if (token_info.kind.is_opening_symbol()) {
  975. output_stream << ", closing_token: "
  976. << GetMatchedClosingToken(token).index;
  977. } else if (token_info.kind.is_closing_symbol()) {
  978. output_stream << ", opening_token: "
  979. << GetMatchedOpeningToken(token).index;
  980. }
  981. break;
  982. }
  983. if (token_info.has_trailing_space) {
  984. output_stream << ", has_trailing_space: true";
  985. }
  986. if (token_info.is_recovery) {
  987. output_stream << ", recovery: true";
  988. }
  989. output_stream << " },";
  990. }
  991. auto TokenizedBuffer::GetLineInfo(Line line) -> LineInfo& {
  992. return line_infos_[line.index];
  993. }
  994. auto TokenizedBuffer::GetLineInfo(Line line) const -> const LineInfo& {
  995. return line_infos_[line.index];
  996. }
  997. auto TokenizedBuffer::AddLine(LineInfo info) -> Line {
  998. line_infos_.push_back(info);
  999. return Line(static_cast<int>(line_infos_.size()) - 1);
  1000. }
  1001. auto TokenizedBuffer::GetTokenInfo(Token token) -> TokenInfo& {
  1002. return token_infos_[token.index];
  1003. }
  1004. auto TokenizedBuffer::GetTokenInfo(Token token) const -> const TokenInfo& {
  1005. return token_infos_[token.index];
  1006. }
  1007. auto TokenizedBuffer::AddToken(TokenInfo info) -> Token {
  1008. token_infos_.push_back(info);
  1009. expected_parse_tree_size_ += info.kind.expected_parse_tree_size();
  1010. return Token(static_cast<int>(token_infos_.size()) - 1);
  1011. }
  1012. auto TokenIterator::Print(llvm::raw_ostream& output) const -> void {
  1013. output << token_.index;
  1014. }
  1015. auto TokenizedBuffer::SourceBufferLocationTranslator::GetLocation(
  1016. const char* loc) -> DiagnosticLocation {
  1017. CARBON_CHECK(StringRefContainsPointer(buffer_->source_->text(), loc))
  1018. << "location not within buffer";
  1019. int64_t offset = loc - buffer_->source_->text().begin();
  1020. // Find the first line starting after the given location. Note that we can't
  1021. // inspect `line.length` here because it is not necessarily correct for the
  1022. // final line during lexing (but will be correct later for the parse tree).
  1023. const auto* line_it = std::partition_point(
  1024. buffer_->line_infos_.begin(), buffer_->line_infos_.end(),
  1025. [offset](const LineInfo& line) { return line.start <= offset; });
  1026. // Step back one line to find the line containing the given position.
  1027. CARBON_CHECK(line_it != buffer_->line_infos_.begin())
  1028. << "location precedes the start of the first line";
  1029. --line_it;
  1030. int line_number = line_it - buffer_->line_infos_.begin();
  1031. int column_number = offset - line_it->start;
  1032. // Start by grabbing the line from the buffer. If the line isn't fully lexed,
  1033. // the length will be npos and the line will be grabbed from the known start
  1034. // to the end of the buffer; we'll then adjust the length.
  1035. llvm::StringRef line =
  1036. buffer_->source_->text().substr(line_it->start, line_it->length);
  1037. if (line_it->length == static_cast<int32_t>(llvm::StringRef::npos)) {
  1038. CARBON_CHECK(line.take_front(column_number).count('\n') == 0)
  1039. << "Currently we assume no unlexed newlines prior to the error column, "
  1040. "but there was one when erroring at "
  1041. << buffer_->source_->filename() << ":" << line_number << ":"
  1042. << column_number;
  1043. // Look for the next newline since we don't know the length. We can start at
  1044. // the column because prior newlines will have been lexed.
  1045. auto end_newline_pos = line.find('\n', column_number);
  1046. if (end_newline_pos != llvm::StringRef::npos) {
  1047. line = line.take_front(end_newline_pos);
  1048. }
  1049. }
  1050. return {.file_name = buffer_->source_->filename(),
  1051. .line = line,
  1052. .line_number = line_number + 1,
  1053. .column_number = column_number + 1};
  1054. }
  1055. auto TokenLocationTranslator::GetLocation(Token token) -> DiagnosticLocation {
  1056. // Map the token location into a position within the source buffer.
  1057. const auto& token_info = buffer_->GetTokenInfo(token);
  1058. const auto& line_info = buffer_->GetLineInfo(token_info.token_line);
  1059. const char* token_start =
  1060. buffer_->source_->text().begin() + line_info.start + token_info.column;
  1061. // Find the corresponding file location.
  1062. // TODO: Should we somehow indicate in the diagnostic location if this token
  1063. // is a recovery token that doesn't correspond to the original source?
  1064. return TokenizedBuffer::SourceBufferLocationTranslator(buffer_).GetLocation(
  1065. token_start);
  1066. }
  1067. } // namespace Carbon::Lex