lex.cpp 69 KB

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