lex.cpp 65 KB

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