lex.cpp 62 KB

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