tokenized_buffer.cpp 54 KB

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