lex.cpp 65 KB

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