tokenized_buffer.cpp 62 KB

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