lex.cpp 56 KB

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