lex.cpp 60 KB

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