lex.cpp 70 KB

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