lex.cpp 69 KB

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