lex.cpp 65 KB

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