lex.cpp 52 KB

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