lex.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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. // Any comment must be the only non-whitespace on the line.
  758. const auto* line_info = current_line_info();
  759. if (LLVM_UNLIKELY(position != line_info->start + line_info->indent)) {
  760. CARBON_DIAGNOSTIC(TrailingComment, Error,
  761. "Trailing comments are not permitted.");
  762. emitter_.Emit(source_text.begin() + position, TrailingComment);
  763. // Note that we cannot fall-through here as the logic below doesn't handle
  764. // trailing comments. Instead, we treat trailing comments as vertical
  765. // whitespace, which already is designed to skip over any erroneous text at
  766. // the end of the line.
  767. LexVerticalWhitespace(source_text, position);
  768. return;
  769. }
  770. // The introducer '//' must be followed by whitespace or EOF.
  771. bool is_valid_after_slashes = true;
  772. if (position + 2 < static_cast<ssize_t>(source_text.size()) &&
  773. LLVM_UNLIKELY(!IsSpace(source_text[position + 2]))) {
  774. CARBON_DIAGNOSTIC(NoWhitespaceAfterCommentIntroducer, Error,
  775. "Whitespace is required after '//'.");
  776. emitter_.Emit(source_text.begin() + position + 2,
  777. NoWhitespaceAfterCommentIntroducer);
  778. // We use this to tweak the lexing of blocks below.
  779. is_valid_after_slashes = false;
  780. }
  781. // Skip over this line.
  782. ssize_t line_index = line_index_;
  783. ++line_index;
  784. position = buffer_.line_infos_[line_index].start;
  785. // A very common pattern is a long block of comment lines all with the same
  786. // indent and comment start. We skip these comment blocks in bulk both for
  787. // speed and to reduce redundant diagnostics if each line has the same
  788. // erroneous comment start like `//!`.
  789. //
  790. // When we have SIMD support this is even more important for speed, as short
  791. // indents can be scanned extremely quickly with SIMD and we expect these to
  792. // be the dominant cases.
  793. //
  794. // TODO: We should extend this to 32-byte SIMD on platforms with support.
  795. constexpr int MaxIndent = 13;
  796. const int indent = line_info->indent;
  797. const ssize_t first_line_start = line_info->start;
  798. ssize_t prefix_size = indent + (is_valid_after_slashes ? 3 : 2);
  799. auto skip_to_next_line = [this, indent, &line_index, &position] {
  800. // We're guaranteed to have a line here even on a comment on the last line
  801. // as we ensure there is an empty line structure at the end of every file.
  802. ++line_index;
  803. auto* next_line_info = &buffer_.line_infos_[line_index];
  804. next_line_info->indent = indent;
  805. position = next_line_info->start;
  806. };
  807. if (CARBON_USE_SIMD &&
  808. position + 16 < static_cast<ssize_t>(source_text.size()) &&
  809. indent <= MaxIndent) {
  810. // Load a mask based on the amount of text we want to compare.
  811. auto mask = PrefixMasks[prefix_size];
  812. #if __ARM_NEON
  813. // Load and mask the prefix of the current line.
  814. auto prefix = vld1q_u8(reinterpret_cast<const uint8_t*>(source_text.data() +
  815. first_line_start));
  816. prefix = vandq_u8(mask, prefix);
  817. do {
  818. // Load and mask the next line to consider's prefix.
  819. auto next_prefix = vld1q_u8(
  820. reinterpret_cast<const uint8_t*>(source_text.data() + position));
  821. next_prefix = vandq_u8(mask, next_prefix);
  822. // Compare the two prefixes and if any lanes differ, break.
  823. auto compare = vceqq_u8(prefix, next_prefix);
  824. if (vminvq_u8(compare) == 0) {
  825. break;
  826. }
  827. skip_to_next_line();
  828. } while (position + 16 < static_cast<ssize_t>(source_text.size()));
  829. #elif __x86_64__
  830. // Use the current line's prefix as the exemplar to compare against.
  831. // We don't mask here as we will mask when doing the comparison.
  832. auto prefix = _mm_loadu_si128(reinterpret_cast<const __m128i*>(
  833. source_text.data() + first_line_start));
  834. do {
  835. // Load the next line to consider's prefix.
  836. auto next_prefix = _mm_loadu_si128(
  837. reinterpret_cast<const __m128i*>(source_text.data() + position));
  838. // Compute the difference between the next line and our exemplar. Again,
  839. // we don't mask the difference because the comparison below will be
  840. // masked.
  841. auto prefix_diff = _mm_xor_si128(prefix, next_prefix);
  842. // If we have any differences (non-zero bits) within the mask, we can't
  843. // skip the next line too.
  844. if (!_mm_test_all_zeros(mask, prefix_diff)) {
  845. break;
  846. }
  847. skip_to_next_line();
  848. } while (position + 16 < static_cast<ssize_t>(source_text.size()));
  849. #else
  850. #error "Unsupported SIMD architecture!"
  851. #endif
  852. // TODO: If we finish the loop due to the position approaching the end of
  853. // the buffer we may fail to skip the last line in a comment block that
  854. // has an invalid initial sequence and thus emit extra diagnostics. We
  855. // should really fall through to the generic skipping logic, but the code
  856. // organization will need to change significantly to allow that.
  857. } else {
  858. while (position + prefix_size < static_cast<ssize_t>(source_text.size()) &&
  859. memcmp(source_text.data() + first_line_start,
  860. source_text.data() + position, prefix_size) == 0) {
  861. skip_to_next_line();
  862. }
  863. }
  864. // Now compute the indent of this next line before we finish.
  865. ssize_t line_start = position;
  866. SkipHorizontalWhitespace(source_text, position);
  867. // Now that we're done scanning, update to the latest line index and indent.
  868. line_index_ = line_index;
  869. current_line_info()->indent = position - line_start;
  870. }
  871. auto Lexer::LexNumericLiteral(llvm::StringRef source_text, ssize_t& position)
  872. -> LexResult {
  873. std::optional<NumericLiteral> literal =
  874. NumericLiteral::Lex(source_text.substr(position));
  875. if (!literal) {
  876. return LexError(source_text, position);
  877. }
  878. // Capture the position before we step past the token.
  879. int32_t byte_offset = position;
  880. int token_size = literal->text().size();
  881. position += token_size;
  882. return VariantMatch(
  883. literal->ComputeValue(emitter_),
  884. [&](NumericLiteral::IntValue&& value) {
  885. return LexTokenWithPayload(
  886. TokenKind::IntLiteral,
  887. buffer_.value_stores_->ints().Add(std::move(value.value)).index,
  888. byte_offset);
  889. },
  890. [&](NumericLiteral::RealValue&& value) {
  891. auto real_id = buffer_.value_stores_->reals().Add(Real{
  892. .mantissa = value.mantissa,
  893. .exponent = value.exponent,
  894. .is_decimal = (value.radix == NumericLiteral::Radix::Decimal)});
  895. return LexTokenWithPayload(TokenKind::RealLiteral, real_id.index,
  896. byte_offset);
  897. },
  898. [&](NumericLiteral::UnrecoverableError) {
  899. return LexTokenWithPayload(TokenKind::Error, token_size, byte_offset);
  900. });
  901. }
  902. auto Lexer::LexStringLiteral(llvm::StringRef source_text, ssize_t& position)
  903. -> LexResult {
  904. std::optional<StringLiteral> literal =
  905. StringLiteral::Lex(source_text.substr(position));
  906. if (!literal) {
  907. return LexError(source_text, position);
  908. }
  909. // Capture the position before we step past the token.
  910. int32_t byte_offset = position;
  911. int string_column = byte_offset - current_line_info()->start;
  912. ssize_t literal_size = literal->text().size();
  913. position += literal_size;
  914. // Update line and column information.
  915. if (literal->is_multi_line()) {
  916. while (next_line_info()->start < position) {
  917. ++line_index_;
  918. current_line_info()->indent = string_column;
  919. }
  920. // Note that we've updated the current line at this point, but
  921. // `set_indent_` is already true from above. That remains correct as the
  922. // last line of the multi-line literal *also* has its indent set.
  923. }
  924. if (literal->is_terminated()) {
  925. auto string_id = buffer_.value_stores_->string_literal_values().Add(
  926. literal->ComputeValue(buffer_.allocator_, emitter_));
  927. return LexTokenWithPayload(TokenKind::StringLiteral, string_id.index,
  928. byte_offset);
  929. } else {
  930. CARBON_DIAGNOSTIC(UnterminatedString, Error,
  931. "String is missing a terminator.");
  932. emitter_.Emit(literal->text().begin(), UnterminatedString);
  933. return LexTokenWithPayload(TokenKind::Error, literal_size, byte_offset);
  934. }
  935. }
  936. auto Lexer::LexOneCharSymbolToken(llvm::StringRef source_text, TokenKind kind,
  937. ssize_t& position) -> TokenIndex {
  938. // Verify in a debug build that the incoming token kind is correct.
  939. CARBON_DCHECK(kind != TokenKind::Error);
  940. CARBON_DCHECK(kind.fixed_spelling().size() == 1);
  941. CARBON_DCHECK(source_text[position] == kind.fixed_spelling().front())
  942. << "Source text starts with '" << source_text[position]
  943. << "' instead of the spelling '" << kind.fixed_spelling()
  944. << "' of the incoming token kind '" << kind << "'";
  945. TokenIndex token = LexToken(kind, position);
  946. ++position;
  947. return token;
  948. }
  949. auto Lexer::LexOpeningSymbolToken(llvm::StringRef source_text, TokenKind kind,
  950. ssize_t& position) -> LexResult {
  951. CARBON_DCHECK(kind.is_opening_symbol());
  952. CARBON_DCHECK(kind.fixed_spelling().size() == 1);
  953. CARBON_DCHECK(source_text[position] == kind.fixed_spelling().front())
  954. << "Source text starts with '" << source_text[position]
  955. << "' instead of the spelling '" << kind.fixed_spelling()
  956. << "' of the incoming token kind '" << kind << "'";
  957. int32_t byte_offset = position;
  958. ++position;
  959. // Lex the opening symbol with a zero closing index. We'll add a payload later
  960. // when we match a closing symbol or in recovery.
  961. TokenIndex token = LexToken(kind, byte_offset);
  962. open_groups_.push_back(token);
  963. return token;
  964. }
  965. auto Lexer::LexClosingSymbolToken(llvm::StringRef source_text, TokenKind kind,
  966. ssize_t& position) -> LexResult {
  967. CARBON_DCHECK(kind.is_closing_symbol());
  968. CARBON_DCHECK(kind.fixed_spelling().size() == 1);
  969. CARBON_DCHECK(source_text[position] == kind.fixed_spelling().front())
  970. << "Source text starts with '" << source_text[position]
  971. << "' instead of the spelling '" << kind.fixed_spelling()
  972. << "' of the incoming token kind '" << kind << "'";
  973. int32_t byte_offset = position;
  974. ++position;
  975. // If there's not a matching opening symbol, just track that we had an error.
  976. // We will diagnose and recover when we reach the end of the file. See
  977. // `DiagnoseAndFixMismatchedBrackets` for details.
  978. if (LLVM_UNLIKELY(open_groups_.empty())) {
  979. has_mismatched_brackets_ = true;
  980. // Lex without a matching index payload -- we'll add one during recovery.
  981. return LexToken(kind, byte_offset);
  982. }
  983. TokenIndex opening_token = open_groups_.pop_back_val();
  984. TokenIndex token =
  985. LexTokenWithPayload(kind, opening_token.index, byte_offset);
  986. auto& opening_token_info = buffer_.GetTokenInfo(opening_token);
  987. if (LLVM_UNLIKELY(opening_token_info.kind() != kind.opening_symbol())) {
  988. has_mismatched_brackets_ = true;
  989. buffer_.GetTokenInfo(token).set_opening_token_index(TokenIndex::Invalid);
  990. return token;
  991. }
  992. opening_token_info.set_closing_token_index(token);
  993. return token;
  994. }
  995. auto Lexer::LexSymbolToken(llvm::StringRef source_text, ssize_t& position)
  996. -> LexResult {
  997. // One character symbols and grouping symbols are handled with dedicated
  998. // dispatch. We only lex the multi-character tokens here.
  999. TokenKind kind = llvm::StringSwitch<TokenKind>(source_text.substr(position))
  1000. #define CARBON_SYMBOL_TOKEN(Name, Spelling) \
  1001. .StartsWith(Spelling, TokenKind::Name)
  1002. #define CARBON_ONE_CHAR_SYMBOL_TOKEN(TokenName, Spelling)
  1003. #define CARBON_OPENING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, ClosingName)
  1004. #define CARBON_CLOSING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, OpeningName)
  1005. #include "toolchain/lex/token_kind.def"
  1006. .Default(TokenKind::Error);
  1007. if (kind == TokenKind::Error) {
  1008. return LexError(source_text, position);
  1009. }
  1010. TokenIndex token = LexToken(kind, position);
  1011. position += kind.fixed_spelling().size();
  1012. return token;
  1013. }
  1014. auto Lexer::LexWordAsTypeLiteralToken(llvm::StringRef word, int32_t byte_offset)
  1015. -> LexResult {
  1016. if (word.size() < 2) {
  1017. // Too short to form one of these tokens.
  1018. return LexResult::NoMatch();
  1019. }
  1020. if (word[1] < '1' || word[1] > '9') {
  1021. // Doesn't start with a valid initial digit.
  1022. return LexResult::NoMatch();
  1023. }
  1024. TokenKind kind;
  1025. switch (word.front()) {
  1026. case 'i':
  1027. kind = TokenKind::IntTypeLiteral;
  1028. break;
  1029. case 'u':
  1030. kind = TokenKind::UnsignedIntTypeLiteral;
  1031. break;
  1032. case 'f':
  1033. kind = TokenKind::FloatTypeLiteral;
  1034. break;
  1035. default:
  1036. return LexResult::NoMatch();
  1037. };
  1038. llvm::StringRef suffix = word.substr(1);
  1039. if (!CanLexInt(emitter_, suffix)) {
  1040. return LexTokenWithPayload(TokenKind::Error, word.size(), byte_offset);
  1041. }
  1042. llvm::APInt suffix_value;
  1043. if (suffix.getAsInteger(10, suffix_value)) {
  1044. return LexResult::NoMatch();
  1045. }
  1046. return LexTokenWithPayload(
  1047. kind, buffer_.value_stores_->ints().Add(std::move(suffix_value)).index,
  1048. byte_offset);
  1049. }
  1050. auto Lexer::LexKeywordOrIdentifier(llvm::StringRef source_text,
  1051. ssize_t& position) -> LexResult {
  1052. if (static_cast<unsigned char>(source_text[position]) > 0x7F) {
  1053. // TODO: Need to add support for Unicode lexing.
  1054. return LexError(source_text, position);
  1055. }
  1056. CARBON_CHECK(
  1057. IsIdStartByteTable[static_cast<unsigned char>(source_text[position])]);
  1058. // Capture the position before we step past the token.
  1059. int32_t byte_offset = position;
  1060. // Take the valid characters off the front of the source buffer.
  1061. llvm::StringRef identifier_text =
  1062. ScanForIdentifierPrefix(source_text.substr(position));
  1063. CARBON_CHECK(!identifier_text.empty()) << "Must have at least one character!";
  1064. position += identifier_text.size();
  1065. // Check if the text is a type literal, and if so form such a literal.
  1066. if (LexResult result =
  1067. LexWordAsTypeLiteralToken(identifier_text, byte_offset)) {
  1068. return result;
  1069. }
  1070. // Check if the text matches a keyword token, and if so use that.
  1071. TokenKind kind = llvm::StringSwitch<TokenKind>(identifier_text)
  1072. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, TokenKind::Name)
  1073. #include "toolchain/lex/token_kind.def"
  1074. .Default(TokenKind::Error);
  1075. if (kind != TokenKind::Error) {
  1076. return LexToken(kind, byte_offset);
  1077. }
  1078. // Otherwise we have a generic identifier.
  1079. return LexTokenWithPayload(
  1080. TokenKind::Identifier,
  1081. buffer_.value_stores_->identifiers().Add(identifier_text).index,
  1082. byte_offset);
  1083. }
  1084. auto Lexer::LexHash(llvm::StringRef source_text, ssize_t& position)
  1085. -> LexResult {
  1086. // For `r#`, we already lexed an `r` identifier token. Detect that case and
  1087. // replace that token with a raw identifier. We do this to keep identifier
  1088. // lexing as fast as possible.
  1089. // Look for the `r` token. Note that this is always in bounds because we
  1090. // create a start of file token.
  1091. auto& prev_token_info = buffer_.token_infos_.back();
  1092. // If the previous token isn't the identifier `r`, or the character after `#`
  1093. // isn't the start of an identifier, this is not a raw identifier.
  1094. if (prev_token_info.kind() != TokenKind::Identifier ||
  1095. source_text[position - 1] != 'r' ||
  1096. position + 1 == static_cast<ssize_t>(source_text.size()) ||
  1097. !IsIdStartByteTable[static_cast<unsigned char>(
  1098. source_text[position + 1])] ||
  1099. prev_token_info.byte_offset() != static_cast<int32_t>(position) - 1) {
  1100. [[clang::musttail]] return LexStringLiteral(source_text, position);
  1101. }
  1102. CARBON_DCHECK(buffer_.value_stores_->identifiers().Get(
  1103. prev_token_info.ident_id()) == "r");
  1104. // Take the valid characters off the front of the source buffer.
  1105. llvm::StringRef identifier_text =
  1106. ScanForIdentifierPrefix(source_text.substr(position + 1));
  1107. CARBON_CHECK(!identifier_text.empty()) << "Must have at least one character!";
  1108. position += 1 + identifier_text.size();
  1109. // Replace the `r` identifier's value with the raw identifier.
  1110. // TODO: This token doesn't carry any indicator that it's raw, so
  1111. // diagnostics are unclear.
  1112. prev_token_info.set_ident_id(
  1113. buffer_.value_stores_->identifiers().Add(identifier_text));
  1114. return LexResult(TokenIndex(buffer_.token_infos_.size() - 1));
  1115. }
  1116. auto Lexer::LexError(llvm::StringRef source_text, ssize_t& position)
  1117. -> LexResult {
  1118. llvm::StringRef error_text =
  1119. source_text.substr(position).take_while([](char c) {
  1120. if (IsAlnum(c)) {
  1121. return false;
  1122. }
  1123. switch (c) {
  1124. case '_':
  1125. case '\t':
  1126. case '\n':
  1127. return false;
  1128. default:
  1129. break;
  1130. }
  1131. return llvm::StringSwitch<bool>(llvm::StringRef(&c, 1))
  1132. #define CARBON_SYMBOL_TOKEN(Name, Spelling) .StartsWith(Spelling, false)
  1133. #include "toolchain/lex/token_kind.def"
  1134. .Default(true);
  1135. });
  1136. if (error_text.empty()) {
  1137. // TODO: Reimplement this to use the lexer properly. In the meantime,
  1138. // guarantee that we eat at least one byte.
  1139. error_text = source_text.substr(position, 1);
  1140. }
  1141. auto token =
  1142. LexTokenWithPayload(TokenKind::Error, error_text.size(), position);
  1143. CARBON_DIAGNOSTIC(UnrecognizedCharacters, Error,
  1144. "Encountered unrecognized characters while parsing.");
  1145. emitter_.Emit(error_text.begin(), UnrecognizedCharacters);
  1146. position += error_text.size();
  1147. return token;
  1148. }
  1149. auto Lexer::LexFileStart(llvm::StringRef source_text, ssize_t& position)
  1150. -> void {
  1151. CARBON_CHECK(position == 0);
  1152. // Before lexing any source text, add the start-of-file token so that code
  1153. // can assume a non-empty token buffer for the rest of lexing.
  1154. LexToken(TokenKind::FileStart, 0);
  1155. // The file start also represents whitespace.
  1156. NoteWhitespace();
  1157. // Also skip any horizontal whitespace and record the indentation of the
  1158. // first line.
  1159. SkipHorizontalWhitespace(source_text, position);
  1160. auto* line_info = current_line_info();
  1161. CARBON_CHECK(line_info->start == 0);
  1162. line_info->indent = position;
  1163. }
  1164. auto Lexer::LexFileEnd(llvm::StringRef source_text, ssize_t position) -> void {
  1165. CARBON_CHECK(position == static_cast<ssize_t>(source_text.size()));
  1166. // Check if the last line is empty and not the first line (and only). If so,
  1167. // re-pin the last line to be the prior one so that diagnostics and editors
  1168. // can treat newlines as terminators even though we internally handle them
  1169. // as separators in case of a missing newline on the last line. We do this
  1170. // here instead of detecting this when we see the newline to avoid more
  1171. // conditions along that fast path.
  1172. if (position == current_line_info()->start && line_index_ != 0) {
  1173. --line_index_;
  1174. --position;
  1175. }
  1176. // The end-of-file token is always considered to be whitespace.
  1177. NoteWhitespace();
  1178. LexToken(TokenKind::FileEnd, position);
  1179. // If we had any mismatched brackets, issue diagnostics and fix them.
  1180. if (has_mismatched_brackets_ || !open_groups_.empty()) {
  1181. DiagnoseAndFixMismatchedBrackets();
  1182. }
  1183. }
  1184. // A list of pending insertions to make into a tokenized buffer for error
  1185. // recovery. These are buffered so that we can perform them in linear time.
  1186. class Lexer::ErrorRecoveryBuffer {
  1187. public:
  1188. explicit ErrorRecoveryBuffer(TokenizedBuffer& buffer) : buffer_(buffer) {}
  1189. auto empty() const -> bool {
  1190. return new_tokens_.empty() && !any_error_tokens_;
  1191. }
  1192. // Insert a recovery token of kind `kind` before `insert_before`. Note that we
  1193. // currently require insertions to be specified in source order, but this
  1194. // restriction would be easy to relax.
  1195. auto InsertBefore(TokenIndex insert_before, TokenKind kind) -> void {
  1196. CARBON_CHECK(insert_before.index > 0)
  1197. << "Cannot insert before the start of file token.";
  1198. CARBON_CHECK(insert_before.index <
  1199. static_cast<int>(buffer_.token_infos_.size()))
  1200. << "Cannot insert after the end of file token.";
  1201. CARBON_CHECK(new_tokens_.empty() ||
  1202. new_tokens_.back().first <= insert_before)
  1203. << "Insertions performed out of order.";
  1204. // If the `insert_before` token has leading whitespace, mark the
  1205. // inserted token as also having leading whitespace. This avoids changing
  1206. // whether the prior tokens had leading or trailing whitespace when
  1207. // inserting.
  1208. bool insert_leading_space = buffer_.HasLeadingWhitespace(insert_before);
  1209. // Find the end of the token before the target token, and add the new token
  1210. // there.
  1211. TokenIndex insert_after(insert_before.index - 1);
  1212. const auto& prev_info = buffer_.GetTokenInfo(insert_after);
  1213. int32_t byte_offset =
  1214. prev_info.byte_offset() + buffer_.GetTokenText(insert_after).size();
  1215. new_tokens_.push_back(
  1216. {insert_before, TokenInfo(kind, insert_leading_space, byte_offset)});
  1217. }
  1218. // Replace the given token with an error token. We do this immediately,
  1219. // because we don't benefit from buffering it.
  1220. auto ReplaceWithError(TokenIndex token) -> void {
  1221. auto& token_info = buffer_.GetTokenInfo(token);
  1222. int error_length = buffer_.GetTokenText(token).size();
  1223. token_info.ResetAsError(error_length);
  1224. any_error_tokens_ = true;
  1225. }
  1226. // Merge the recovery tokens into the token list of the tokenized buffer.
  1227. auto Apply() -> void {
  1228. auto old_tokens = std::move(buffer_.token_infos_);
  1229. buffer_.token_infos_.clear();
  1230. int new_size = old_tokens.size() + new_tokens_.size();
  1231. buffer_.token_infos_.reserve(new_size);
  1232. buffer_.recovery_tokens_.resize(new_size);
  1233. int old_tokens_offset = 0;
  1234. for (auto [next_offset, info] : new_tokens_) {
  1235. buffer_.token_infos_.append(old_tokens.begin() + old_tokens_offset,
  1236. old_tokens.begin() + next_offset.index);
  1237. buffer_.AddToken(info);
  1238. buffer_.recovery_tokens_.set(next_offset.index);
  1239. old_tokens_offset = next_offset.index;
  1240. }
  1241. buffer_.token_infos_.append(old_tokens.begin() + old_tokens_offset,
  1242. old_tokens.end());
  1243. }
  1244. // Perform bracket matching to fix cross-references between tokens. This must
  1245. // be done after all recovery is performed and all brackets match, because
  1246. // recovery will change token indexes.
  1247. auto FixTokenCrossReferences() -> void {
  1248. llvm::SmallVector<TokenIndex> open_groups;
  1249. for (auto token : buffer_.tokens()) {
  1250. auto kind = buffer_.GetKind(token);
  1251. if (kind.is_opening_symbol()) {
  1252. open_groups.push_back(token);
  1253. } else if (kind.is_closing_symbol()) {
  1254. CARBON_CHECK(!open_groups.empty()) << "Failed to balance brackets";
  1255. auto opening_token = open_groups.pop_back_val();
  1256. CARBON_CHECK(
  1257. kind == buffer_.GetTokenInfo(opening_token).kind().closing_symbol())
  1258. << "Failed to balance brackets";
  1259. auto& opening_token_info = buffer_.GetTokenInfo(opening_token);
  1260. auto& closing_token_info = buffer_.GetTokenInfo(token);
  1261. opening_token_info.set_closing_token_index(token);
  1262. closing_token_info.set_opening_token_index(opening_token);
  1263. }
  1264. }
  1265. }
  1266. private:
  1267. TokenizedBuffer& buffer_;
  1268. // A list of tokens to insert into the token stream to fix mismatched
  1269. // brackets. The first element in each pair is the original token index to
  1270. // insert the new token before.
  1271. llvm::SmallVector<std::pair<TokenIndex, TokenizedBuffer::TokenInfo>>
  1272. new_tokens_;
  1273. // Whether we have changed any tokens into error tokens.
  1274. bool any_error_tokens_ = false;
  1275. };
  1276. // Issue an UnmatchedOpening diagnostic.
  1277. static auto DiagnoseUnmatchedOpening(TokenDiagnosticEmitter& emitter,
  1278. TokenIndex opening_token) -> void {
  1279. CARBON_DIAGNOSTIC(UnmatchedOpening, Error,
  1280. "Opening symbol without a corresponding closing symbol.");
  1281. emitter.Emit(opening_token, UnmatchedOpening);
  1282. }
  1283. // If brackets didn't pair or nest properly, find a set of places to insert
  1284. // brackets to fix the nesting, issue suitable diagnostics, and update the
  1285. // token list to describe the fixes.
  1286. auto Lexer::DiagnoseAndFixMismatchedBrackets() -> void {
  1287. ErrorRecoveryBuffer fixes(buffer_);
  1288. // Look for mismatched brackets and decide where to add tokens to fix them.
  1289. //
  1290. // TODO: For now, we use a greedy algorithm for this. We could do better by
  1291. // taking indentation into account. For example:
  1292. //
  1293. // 1 fn F() {
  1294. // 2 if (thing1)
  1295. // 3 thing2;
  1296. // 4 }
  1297. // 5 }
  1298. //
  1299. // Here, we'll match the `{` on line 1 with the `}` on line 4, and then
  1300. // report that the `}` on line 5 is unmatched. Instead, we should notice that
  1301. // line 1 matches better with line 5 due to indentation, and work out that
  1302. // the missing `{` was on line 2, also based on indentation.
  1303. open_groups_.clear();
  1304. for (auto token : buffer_.tokens()) {
  1305. auto kind = buffer_.GetKind(token);
  1306. if (kind.is_opening_symbol()) {
  1307. open_groups_.push_back(token);
  1308. continue;
  1309. }
  1310. if (!kind.is_closing_symbol()) {
  1311. continue;
  1312. }
  1313. // Find the innermost matching opening symbol.
  1314. auto opening_it = std::find_if(
  1315. open_groups_.rbegin(), open_groups_.rend(),
  1316. [&](TokenIndex opening_token) {
  1317. return buffer_.GetTokenInfo(opening_token).kind().closing_symbol() ==
  1318. kind;
  1319. });
  1320. if (opening_it == open_groups_.rend()) {
  1321. CARBON_DIAGNOSTIC(
  1322. UnmatchedClosing, Error,
  1323. "Closing symbol without a corresponding opening symbol.");
  1324. token_emitter_.Emit(token, UnmatchedClosing);
  1325. fixes.ReplaceWithError(token);
  1326. continue;
  1327. }
  1328. // All intermediate open tokens have no matching close token.
  1329. for (auto it = open_groups_.rbegin(); it != opening_it; ++it) {
  1330. DiagnoseUnmatchedOpening(token_emitter_, *it);
  1331. // Add a closing bracket for the unclosed group here.
  1332. //
  1333. // TODO: Indicate in the diagnostic that we did this, perhaps by
  1334. // annotating the snippet.
  1335. auto opening_kind = buffer_.GetKind(*it);
  1336. fixes.InsertBefore(token, opening_kind.closing_symbol());
  1337. }
  1338. open_groups_.erase(opening_it.base() - 1, open_groups_.end());
  1339. }
  1340. // Diagnose any remaining unmatched opening symbols.
  1341. for (auto token : open_groups_) {
  1342. // We don't have a good location to insert a close bracket. Convert the
  1343. // opening token from a bracket to an error.
  1344. DiagnoseUnmatchedOpening(token_emitter_, token);
  1345. fixes.ReplaceWithError(token);
  1346. }
  1347. CARBON_CHECK(!fixes.empty()) << "Didn't find anything to fix";
  1348. fixes.Apply();
  1349. fixes.FixTokenCrossReferences();
  1350. }
  1351. auto Lex(SharedValueStores& value_stores, SourceBuffer& source,
  1352. DiagnosticConsumer& consumer) -> TokenizedBuffer {
  1353. return Lexer(value_stores, source, consumer).Lex();
  1354. }
  1355. } // namespace Carbon::Lex