tokenized_buffer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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/lexer/tokenized_buffer.h"
  5. #include <algorithm>
  6. #include <array>
  7. #include <cmath>
  8. #include <iterator>
  9. #include <string>
  10. #include "common/check.h"
  11. #include "common/string_helpers.h"
  12. #include "llvm/ADT/STLExtras.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/StringSwitch.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include "llvm/Support/ErrorHandling.h"
  17. #include "llvm/Support/Format.h"
  18. #include "llvm/Support/FormatVariadic.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include "toolchain/lexer/character_set.h"
  21. #include "toolchain/lexer/lex_helpers.h"
  22. #include "toolchain/lexer/numeric_literal.h"
  23. #include "toolchain/lexer/string_literal.h"
  24. namespace Carbon {
  25. struct TrailingComment : DiagnosticBase<TrailingComment> {
  26. static constexpr llvm::StringLiteral ShortName = "syntax-comments";
  27. static constexpr llvm::StringLiteral Message =
  28. "Trailing comments are not permitted.";
  29. };
  30. struct NoWhitespaceAfterCommentIntroducer
  31. : DiagnosticBase<NoWhitespaceAfterCommentIntroducer> {
  32. static constexpr llvm::StringLiteral ShortName = "syntax-comments";
  33. static constexpr llvm::StringLiteral Message =
  34. "Whitespace is required after '//'.";
  35. };
  36. struct UnmatchedClosing : DiagnosticBase<UnmatchedClosing> {
  37. static constexpr llvm::StringLiteral ShortName = "syntax-balanced-delimiters";
  38. static constexpr llvm::StringLiteral Message =
  39. "Closing symbol without a corresponding opening symbol.";
  40. };
  41. struct MismatchedClosing : DiagnosticBase<MismatchedClosing> {
  42. static constexpr llvm::StringLiteral ShortName = "syntax-balanced-delimiters";
  43. static constexpr llvm::StringLiteral Message =
  44. "Closing symbol does not match most recent opening symbol.";
  45. };
  46. struct UnrecognizedCharacters : DiagnosticBase<UnrecognizedCharacters> {
  47. static constexpr llvm::StringLiteral ShortName =
  48. "syntax-unrecognized-characters";
  49. static constexpr llvm::StringLiteral Message =
  50. "Encountered unrecognized characters while parsing.";
  51. };
  52. struct UnterminatedString : DiagnosticBase<UnterminatedString> {
  53. static constexpr llvm::StringLiteral ShortName = "syntax-string-terminator";
  54. static constexpr llvm::StringLiteral Message =
  55. "String is missing a terminator.";
  56. };
  57. // TODO: Move Overload and VariantMatch somewhere more central.
  58. // Form an overload set from a list of functions. For example:
  59. //
  60. // ```
  61. // auto overloaded = Overload{[] (int) {}, [] (float) {}};
  62. // ```
  63. template <typename... Fs>
  64. struct Overload : Fs... {
  65. using Fs::operator()...;
  66. };
  67. template <typename... Fs>
  68. Overload(Fs...) -> Overload<Fs...>;
  69. // Pattern-match against the type of the value stored in the variant `V`. Each
  70. // element of `fs` should be a function that takes one or more of the variant
  71. // values in `V`.
  72. template <typename V, typename... Fs>
  73. auto VariantMatch(V&& v, Fs&&... fs) -> decltype(auto) {
  74. return std::visit(Overload{std::forward<Fs&&>(fs)...}, std::forward<V&&>(v));
  75. }
  76. // Implementation of the lexer logic itself.
  77. //
  78. // The design is that lexing can loop over the source buffer, consuming it into
  79. // tokens by calling into this API. This class handles the state and breaks down
  80. // the different lexing steps that may be used. It directly updates the provided
  81. // tokenized buffer with the lexed tokens.
  82. class TokenizedBuffer::Lexer {
  83. public:
  84. // Symbolic result of a lexing action. This indicates whether we successfully
  85. // lexed a token, or whether other lexing actions should be attempted.
  86. //
  87. // While it wraps a simple boolean state, its API both helps make the failures
  88. // more self documenting, and by consuming the actual token constructively
  89. // when one is produced, it helps ensure the correct result is returned.
  90. class LexResult {
  91. public:
  92. // Consumes (and discard) a valid token to construct a result
  93. // indicating a token has been produced. Relies on implicit conversions.
  94. // NOLINTNEXTLINE(google-explicit-constructor)
  95. LexResult(Token /*discarded_token*/) : LexResult(true) {}
  96. // Returns a result indicating no token was produced.
  97. static auto NoMatch() -> LexResult { return LexResult(false); }
  98. // Tests whether a token was produced by the lexing routine, and
  99. // the lexer can continue forming tokens.
  100. explicit operator bool() const { return formed_token_; }
  101. private:
  102. explicit LexResult(bool formed_token) : formed_token_(formed_token) {}
  103. bool formed_token_;
  104. };
  105. Lexer(TokenizedBuffer& buffer, DiagnosticConsumer& consumer)
  106. : buffer_(buffer),
  107. translator_(buffer, &current_column_),
  108. emitter_(translator_, consumer),
  109. token_translator_(buffer, &current_column_),
  110. token_emitter_(token_translator_, consumer),
  111. current_line_(buffer.AddLine({0, 0, 0})),
  112. current_line_info_(&buffer.GetLineInfo(current_line_)) {}
  113. // Perform the necessary bookkeeping to step past a newline at the current
  114. // line and column.
  115. auto HandleNewline() -> void {
  116. current_line_info_->length = current_column_;
  117. current_line_ = buffer_.AddLine(
  118. {current_line_info_->start + current_column_ + 1, 0, 0});
  119. current_line_info_ = &buffer_.GetLineInfo(current_line_);
  120. current_column_ = 0;
  121. set_indent_ = false;
  122. }
  123. auto NoteWhitespace() -> void {
  124. if (!buffer_.token_infos_.empty()) {
  125. buffer_.token_infos_.back().has_trailing_space = true;
  126. }
  127. }
  128. auto SkipWhitespace(llvm::StringRef& source_text) -> bool {
  129. const char* const whitespace_start = source_text.begin();
  130. while (!source_text.empty()) {
  131. // We only support line-oriented commenting and lex comments as-if they
  132. // were whitespace.
  133. if (source_text.startswith("//")) {
  134. // Any comment must be the only non-whitespace on the line.
  135. if (set_indent_) {
  136. emitter_.EmitError<TrailingComment>(source_text.begin());
  137. }
  138. // The introducer '//' must be followed by whitespace or EOF.
  139. if (source_text.size() > 2 && !IsSpace(source_text[2])) {
  140. emitter_.EmitError<NoWhitespaceAfterCommentIntroducer>(
  141. source_text.begin() + 2);
  142. }
  143. while (!source_text.empty() && source_text.front() != '\n') {
  144. ++current_column_;
  145. source_text = source_text.drop_front();
  146. }
  147. if (source_text.empty()) {
  148. break;
  149. }
  150. }
  151. switch (source_text.front()) {
  152. default:
  153. // If we find a non-whitespace character without exhausting the
  154. // buffer, return true to continue lexing.
  155. CHECK(!IsSpace(source_text.front()));
  156. if (whitespace_start != source_text.begin()) {
  157. NoteWhitespace();
  158. }
  159. return true;
  160. case '\n':
  161. // If this is the last character in the source, directly return here
  162. // to avoid creating an empty line.
  163. source_text = source_text.drop_front();
  164. if (source_text.empty()) {
  165. current_line_info_->length = current_column_;
  166. return false;
  167. }
  168. // Otherwise, add a line and set up to continue lexing.
  169. HandleNewline();
  170. continue;
  171. case ' ':
  172. case '\t':
  173. // Skip other forms of whitespace while tracking column.
  174. // FIXME: This obviously needs looooots more work to handle unicode
  175. // whitespace as well as special handling to allow better tokenization
  176. // of operators. This is just a stub to check that our column
  177. // management works.
  178. ++current_column_;
  179. source_text = source_text.drop_front();
  180. continue;
  181. }
  182. }
  183. CHECK(source_text.empty()) << "Cannot reach here w/o finishing the text!";
  184. // Update the line length as this is also the end of a line.
  185. current_line_info_->length = current_column_;
  186. return false;
  187. }
  188. auto LexNumericLiteral(llvm::StringRef& source_text) -> LexResult {
  189. llvm::Optional<LexedNumericLiteral> literal =
  190. LexedNumericLiteral::Lex(source_text);
  191. if (!literal) {
  192. return LexResult::NoMatch();
  193. }
  194. int int_column = current_column_;
  195. int token_size = literal->text().size();
  196. current_column_ += token_size;
  197. source_text = source_text.drop_front(token_size);
  198. if (!set_indent_) {
  199. current_line_info_->indent = int_column;
  200. set_indent_ = true;
  201. }
  202. return VariantMatch(
  203. literal->ComputeValue(emitter_),
  204. [&](LexedNumericLiteral::IntegerValue&& value) {
  205. auto token = buffer_.AddToken({.kind = TokenKind::IntegerLiteral(),
  206. .token_line = current_line_,
  207. .column = int_column});
  208. buffer_.GetTokenInfo(token).literal_index =
  209. buffer_.literal_int_storage_.size();
  210. buffer_.literal_int_storage_.push_back(std::move(value.value));
  211. return token;
  212. },
  213. [&](LexedNumericLiteral::RealValue&& value) {
  214. auto token = buffer_.AddToken({.kind = TokenKind::RealLiteral(),
  215. .token_line = current_line_,
  216. .column = int_column});
  217. buffer_.GetTokenInfo(token).literal_index =
  218. buffer_.literal_int_storage_.size();
  219. buffer_.literal_int_storage_.push_back(std::move(value.mantissa));
  220. buffer_.literal_int_storage_.push_back(std::move(value.exponent));
  221. CHECK(buffer_.GetRealLiteral(token).IsDecimal() ==
  222. (value.radix == LexedNumericLiteral::Radix::Decimal));
  223. return token;
  224. },
  225. [&](LexedNumericLiteral::UnrecoverableError) {
  226. auto token = buffer_.AddToken({
  227. .kind = TokenKind::Error(),
  228. .token_line = current_line_,
  229. .column = int_column,
  230. .error_length = token_size,
  231. });
  232. return token;
  233. });
  234. }
  235. auto LexStringLiteral(llvm::StringRef& source_text) -> LexResult {
  236. llvm::Optional<LexedStringLiteral> literal =
  237. LexedStringLiteral::Lex(source_text);
  238. if (!literal) {
  239. return LexResult::NoMatch();
  240. }
  241. Line string_line = current_line_;
  242. int string_column = current_column_;
  243. int literal_size = literal->text().size();
  244. source_text = source_text.drop_front(literal_size);
  245. if (!set_indent_) {
  246. current_line_info_->indent = string_column;
  247. set_indent_ = true;
  248. }
  249. // Update line and column information.
  250. if (!literal->is_multi_line()) {
  251. current_column_ += literal_size;
  252. } else {
  253. for (char c : literal->text()) {
  254. if (c == '\n') {
  255. HandleNewline();
  256. // The indentation of all lines in a multi-line string literal is
  257. // that of the first line.
  258. current_line_info_->indent = string_column;
  259. set_indent_ = true;
  260. } else {
  261. ++current_column_;
  262. }
  263. }
  264. }
  265. if (literal->is_terminated()) {
  266. auto token =
  267. buffer_.AddToken({.kind = TokenKind::StringLiteral(),
  268. .token_line = string_line,
  269. .column = string_column,
  270. .literal_index = static_cast<int32_t>(
  271. buffer_.literal_string_storage_.size())});
  272. buffer_.literal_string_storage_.push_back(
  273. literal->ComputeValue(emitter_));
  274. return token;
  275. } else {
  276. emitter_.EmitError<UnterminatedString>(literal->text().begin());
  277. return buffer_.AddToken({.kind = TokenKind::Error(),
  278. .token_line = string_line,
  279. .column = string_column,
  280. .error_length = literal_size});
  281. }
  282. }
  283. auto LexSymbolToken(llvm::StringRef& source_text) -> LexResult {
  284. TokenKind kind = llvm::StringSwitch<TokenKind>(source_text)
  285. #define CARBON_SYMBOL_TOKEN(Name, Spelling) \
  286. .StartsWith(Spelling, TokenKind::Name())
  287. #include "toolchain/lexer/token_registry.def"
  288. .Default(TokenKind::Error());
  289. if (kind == TokenKind::Error()) {
  290. return LexResult::NoMatch();
  291. }
  292. if (!set_indent_) {
  293. current_line_info_->indent = current_column_;
  294. set_indent_ = true;
  295. }
  296. CloseInvalidOpenGroups(kind);
  297. const char* location = source_text.begin();
  298. Token token = buffer_.AddToken(
  299. {.kind = kind, .token_line = current_line_, .column = current_column_});
  300. current_column_ += kind.GetFixedSpelling().size();
  301. source_text = source_text.drop_front(kind.GetFixedSpelling().size());
  302. // Opening symbols just need to be pushed onto our queue of opening groups.
  303. if (kind.IsOpeningSymbol()) {
  304. open_groups_.push_back(token);
  305. return token;
  306. }
  307. // Only closing symbols need further special handling.
  308. if (!kind.IsClosingSymbol()) {
  309. return token;
  310. }
  311. TokenInfo& closing_token_info = buffer_.GetTokenInfo(token);
  312. // Check that there is a matching opening symbol before we consume this as
  313. // a closing symbol.
  314. if (open_groups_.empty()) {
  315. closing_token_info.kind = TokenKind::Error();
  316. closing_token_info.error_length = kind.GetFixedSpelling().size();
  317. emitter_.EmitError<UnmatchedClosing>(location);
  318. // Note that this still returns true as we do consume a symbol.
  319. return token;
  320. }
  321. // Finally can handle a normal closing symbol.
  322. Token opening_token = open_groups_.pop_back_val();
  323. TokenInfo& opening_token_info = buffer_.GetTokenInfo(opening_token);
  324. opening_token_info.closing_token = token;
  325. closing_token_info.opening_token = opening_token;
  326. return token;
  327. }
  328. // Given a word that has already been lexed, determine whether it is a type
  329. // literal and if so form the corresponding token.
  330. auto LexWordAsTypeLiteralToken(llvm::StringRef word, int column)
  331. -> LexResult {
  332. if (word.size() < 2) {
  333. // Too short to form one of these tokens.
  334. return LexResult::NoMatch();
  335. }
  336. if (!('1' <= word[1] && word[1] <= '9')) {
  337. // Doesn't start with a valid initial digit.
  338. return LexResult::NoMatch();
  339. }
  340. llvm::Optional<TokenKind> kind;
  341. switch (word.front()) {
  342. case 'i':
  343. kind = TokenKind::IntegerTypeLiteral();
  344. break;
  345. case 'u':
  346. kind = TokenKind::UnsignedIntegerTypeLiteral();
  347. break;
  348. case 'f':
  349. kind = TokenKind::FloatingPointTypeLiteral();
  350. break;
  351. default:
  352. return LexResult::NoMatch();
  353. };
  354. llvm::StringRef suffix = word.substr(1);
  355. if (!CanLexInteger(emitter_, suffix)) {
  356. return buffer_.AddToken(
  357. {.kind = TokenKind::Error(),
  358. .token_line = current_line_,
  359. .column = column,
  360. .error_length = static_cast<int32_t>(word.size())});
  361. }
  362. llvm::APInt suffix_value;
  363. if (suffix.getAsInteger(10, suffix_value)) {
  364. return LexResult::NoMatch();
  365. }
  366. auto token = buffer_.AddToken(
  367. {.kind = *kind, .token_line = current_line_, .column = column});
  368. buffer_.GetTokenInfo(token).literal_index =
  369. buffer_.literal_int_storage_.size();
  370. buffer_.literal_int_storage_.push_back(std::move(suffix_value));
  371. return token;
  372. }
  373. // Closes all open groups that cannot remain open across the symbol `K`.
  374. // Users may pass `Error` to close all open groups.
  375. auto CloseInvalidOpenGroups(TokenKind kind) -> void {
  376. if (!kind.IsClosingSymbol() && kind != TokenKind::Error()) {
  377. return;
  378. }
  379. while (!open_groups_.empty()) {
  380. Token opening_token = open_groups_.back();
  381. TokenKind opening_kind = buffer_.GetTokenInfo(opening_token).kind;
  382. if (kind == opening_kind.GetClosingSymbol()) {
  383. return;
  384. }
  385. open_groups_.pop_back();
  386. token_emitter_.EmitError<MismatchedClosing>(opening_token);
  387. CHECK(!buffer_.tokens().empty()) << "Must have a prior opening token!";
  388. Token prev_token = buffer_.tokens().end()[-1];
  389. // TODO: do a smarter backwards scan for where to put the closing
  390. // token.
  391. Token closing_token = buffer_.AddToken(
  392. {.kind = opening_kind.GetClosingSymbol(),
  393. .has_trailing_space = buffer_.HasTrailingWhitespace(prev_token),
  394. .is_recovery = true,
  395. .token_line = current_line_,
  396. .column = current_column_});
  397. TokenInfo& opening_token_info = buffer_.GetTokenInfo(opening_token);
  398. TokenInfo& closing_token_info = buffer_.GetTokenInfo(closing_token);
  399. opening_token_info.closing_token = closing_token;
  400. closing_token_info.opening_token = opening_token;
  401. }
  402. }
  403. auto GetOrCreateIdentifier(llvm::StringRef text) -> Identifier {
  404. auto insert_result = buffer_.identifier_map_.insert(
  405. {text, Identifier(buffer_.identifier_infos_.size())});
  406. if (insert_result.second) {
  407. buffer_.identifier_infos_.push_back({text});
  408. }
  409. return insert_result.first->second;
  410. }
  411. auto LexKeywordOrIdentifier(llvm::StringRef& source_text) -> LexResult {
  412. if (!IsAlpha(source_text.front()) && source_text.front() != '_') {
  413. return LexResult::NoMatch();
  414. }
  415. if (!set_indent_) {
  416. current_line_info_->indent = current_column_;
  417. set_indent_ = true;
  418. }
  419. // Take the valid characters off the front of the source buffer.
  420. llvm::StringRef identifier_text =
  421. source_text.take_while([](char c) { return IsAlnum(c) || c == '_'; });
  422. CHECK(!identifier_text.empty()) << "Must have at least one character!";
  423. int identifier_column = current_column_;
  424. current_column_ += identifier_text.size();
  425. source_text = source_text.drop_front(identifier_text.size());
  426. // Check if the text is a type literal, and if so form such a literal.
  427. if (LexResult result =
  428. LexWordAsTypeLiteralToken(identifier_text, identifier_column)) {
  429. return result;
  430. }
  431. // Check if the text matches a keyword token, and if so use that.
  432. TokenKind kind = llvm::StringSwitch<TokenKind>(identifier_text)
  433. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, TokenKind::Name())
  434. #include "toolchain/lexer/token_registry.def"
  435. .Default(TokenKind::Error());
  436. if (kind != TokenKind::Error()) {
  437. return buffer_.AddToken({.kind = kind,
  438. .token_line = current_line_,
  439. .column = identifier_column});
  440. }
  441. // Otherwise we have a generic identifier.
  442. return buffer_.AddToken({.kind = TokenKind::Identifier(),
  443. .token_line = current_line_,
  444. .column = identifier_column,
  445. .id = GetOrCreateIdentifier(identifier_text)});
  446. }
  447. auto LexError(llvm::StringRef& source_text) -> LexResult {
  448. llvm::StringRef error_text = source_text.take_while([](char c) {
  449. if (IsAlnum(c)) {
  450. return false;
  451. }
  452. switch (c) {
  453. case '_':
  454. case '\t':
  455. case '\n':
  456. return false;
  457. }
  458. return llvm::StringSwitch<bool>(llvm::StringRef(&c, 1))
  459. #define CARBON_SYMBOL_TOKEN(Name, Spelling) .StartsWith(Spelling, false)
  460. #include "toolchain/lexer/token_registry.def"
  461. .Default(true);
  462. });
  463. if (error_text.empty()) {
  464. // TODO: Reimplement this to use the lexer properly. In the meantime,
  465. // guarantee that we eat at least one byte.
  466. error_text = source_text.take_front(1);
  467. }
  468. auto token = buffer_.AddToken(
  469. {.kind = TokenKind::Error(),
  470. .token_line = current_line_,
  471. .column = current_column_,
  472. .error_length = static_cast<int32_t>(error_text.size())});
  473. emitter_.EmitError<UnrecognizedCharacters>(error_text.begin());
  474. current_column_ += error_text.size();
  475. source_text = source_text.drop_front(error_text.size());
  476. return token;
  477. }
  478. auto AddEndOfFileToken() -> void {
  479. buffer_.AddToken({.kind = TokenKind::EndOfFile(),
  480. .token_line = current_line_,
  481. .column = current_column_});
  482. }
  483. private:
  484. TokenizedBuffer& buffer_;
  485. SourceBufferLocationTranslator translator_;
  486. LexerDiagnosticEmitter emitter_;
  487. TokenLocationTranslator token_translator_;
  488. TokenDiagnosticEmitter token_emitter_;
  489. Line current_line_;
  490. LineInfo* current_line_info_;
  491. int current_column_ = 0;
  492. bool set_indent_ = false;
  493. llvm::SmallVector<Token, 8> open_groups_;
  494. };
  495. auto TokenizedBuffer::Lex(SourceBuffer& source, DiagnosticConsumer& consumer)
  496. -> TokenizedBuffer {
  497. TokenizedBuffer buffer(source);
  498. ErrorTrackingDiagnosticConsumer error_tracking_consumer(consumer);
  499. Lexer lexer(buffer, error_tracking_consumer);
  500. llvm::StringRef source_text = source.text();
  501. while (lexer.SkipWhitespace(source_text)) {
  502. // Each time we find non-whitespace characters, try each kind of token we
  503. // support lexing, from simplest to most complex.
  504. Lexer::LexResult result = lexer.LexSymbolToken(source_text);
  505. if (!result) {
  506. result = lexer.LexKeywordOrIdentifier(source_text);
  507. }
  508. if (!result) {
  509. result = lexer.LexNumericLiteral(source_text);
  510. }
  511. if (!result) {
  512. result = lexer.LexStringLiteral(source_text);
  513. }
  514. if (!result) {
  515. result = lexer.LexError(source_text);
  516. }
  517. CHECK(result) << "No token was lexed.";
  518. }
  519. // The end-of-file token is always considered to be whitespace.
  520. lexer.NoteWhitespace();
  521. lexer.CloseInvalidOpenGroups(TokenKind::Error());
  522. lexer.AddEndOfFileToken();
  523. if (error_tracking_consumer.seen_error()) {
  524. buffer.has_errors_ = true;
  525. }
  526. return buffer;
  527. }
  528. auto TokenizedBuffer::GetKind(Token token) const -> TokenKind {
  529. return GetTokenInfo(token).kind;
  530. }
  531. auto TokenizedBuffer::GetLine(Token token) const -> Line {
  532. return GetTokenInfo(token).token_line;
  533. }
  534. auto TokenizedBuffer::GetLineNumber(Token token) const -> int {
  535. return GetLineNumber(GetLine(token));
  536. }
  537. auto TokenizedBuffer::GetColumnNumber(Token token) const -> int {
  538. return GetTokenInfo(token).column + 1;
  539. }
  540. auto TokenizedBuffer::GetTokenText(Token token) const -> llvm::StringRef {
  541. auto& token_info = GetTokenInfo(token);
  542. llvm::StringRef fixed_spelling = token_info.kind.GetFixedSpelling();
  543. if (!fixed_spelling.empty()) {
  544. return fixed_spelling;
  545. }
  546. if (token_info.kind == TokenKind::Error()) {
  547. auto& line_info = GetLineInfo(token_info.token_line);
  548. int64_t token_start = line_info.start + token_info.column;
  549. return source_->text().substr(token_start, token_info.error_length);
  550. }
  551. // Refer back to the source text to preserve oddities like radix or digit
  552. // separators the author included.
  553. if (token_info.kind == TokenKind::IntegerLiteral() ||
  554. token_info.kind == TokenKind::RealLiteral()) {
  555. auto& line_info = GetLineInfo(token_info.token_line);
  556. int64_t token_start = line_info.start + token_info.column;
  557. llvm::Optional<LexedNumericLiteral> relexed_token =
  558. LexedNumericLiteral::Lex(source_->text().substr(token_start));
  559. CHECK(relexed_token) << "Could not reform numeric literal token.";
  560. return relexed_token->text();
  561. }
  562. // Refer back to the source text to find the original spelling, including
  563. // escape sequences etc.
  564. if (token_info.kind == TokenKind::StringLiteral()) {
  565. auto& line_info = GetLineInfo(token_info.token_line);
  566. int64_t token_start = line_info.start + token_info.column;
  567. llvm::Optional<LexedStringLiteral> relexed_token =
  568. LexedStringLiteral::Lex(source_->text().substr(token_start));
  569. CHECK(relexed_token) << "Could not reform string literal token.";
  570. return relexed_token->text();
  571. }
  572. // Refer back to the source text to avoid needing to reconstruct the
  573. // spelling from the size.
  574. if (token_info.kind.IsSizedTypeLiteral()) {
  575. auto& line_info = GetLineInfo(token_info.token_line);
  576. int64_t token_start = line_info.start + token_info.column;
  577. llvm::StringRef suffix =
  578. source_->text().substr(token_start + 1).take_while(IsDecimalDigit);
  579. return llvm::StringRef(suffix.data() - 1, suffix.size() + 1);
  580. }
  581. if (token_info.kind == TokenKind::EndOfFile()) {
  582. return llvm::StringRef();
  583. }
  584. CHECK(token_info.kind == TokenKind::Identifier())
  585. << "Only identifiers have stored text!";
  586. return GetIdentifierText(token_info.id);
  587. }
  588. auto TokenizedBuffer::GetIdentifier(Token token) const -> Identifier {
  589. auto& token_info = GetTokenInfo(token);
  590. CHECK(token_info.kind == TokenKind::Identifier())
  591. << "The token must be an identifier!";
  592. return token_info.id;
  593. }
  594. auto TokenizedBuffer::GetIntegerLiteral(Token token) const
  595. -> const llvm::APInt& {
  596. auto& token_info = GetTokenInfo(token);
  597. CHECK(token_info.kind == TokenKind::IntegerLiteral())
  598. << "The token must be an integer literal!";
  599. return literal_int_storage_[token_info.literal_index];
  600. }
  601. auto TokenizedBuffer::GetRealLiteral(Token token) const -> RealLiteralValue {
  602. auto& token_info = GetTokenInfo(token);
  603. CHECK(token_info.kind == TokenKind::RealLiteral())
  604. << "The token must be a real literal!";
  605. // Note that every real literal is at least three characters long, so we can
  606. // safely look at the second character to determine whether we have a
  607. // decimal or hexadecimal literal.
  608. auto& line_info = GetLineInfo(token_info.token_line);
  609. int64_t token_start = line_info.start + token_info.column;
  610. char second_char = source_->text()[token_start + 1];
  611. bool is_decimal = second_char != 'x' && second_char != 'b';
  612. return RealLiteralValue(this, token_info.literal_index, is_decimal);
  613. }
  614. auto TokenizedBuffer::GetStringLiteral(Token token) const -> llvm::StringRef {
  615. auto& token_info = GetTokenInfo(token);
  616. CHECK(token_info.kind == TokenKind::StringLiteral())
  617. << "The token must be a string literal!";
  618. return literal_string_storage_[token_info.literal_index];
  619. }
  620. auto TokenizedBuffer::GetTypeLiteralSize(Token token) const
  621. -> const llvm::APInt& {
  622. auto& token_info = GetTokenInfo(token);
  623. CHECK(token_info.kind.IsSizedTypeLiteral())
  624. << "The token must be a sized type literal!";
  625. return literal_int_storage_[token_info.literal_index];
  626. }
  627. auto TokenizedBuffer::GetMatchedClosingToken(Token opening_token) const
  628. -> Token {
  629. auto& opening_token_info = GetTokenInfo(opening_token);
  630. CHECK(opening_token_info.kind.IsOpeningSymbol())
  631. << "The token must be an opening group symbol!";
  632. return opening_token_info.closing_token;
  633. }
  634. auto TokenizedBuffer::GetMatchedOpeningToken(Token closing_token) const
  635. -> Token {
  636. auto& closing_token_info = GetTokenInfo(closing_token);
  637. CHECK(closing_token_info.kind.IsClosingSymbol())
  638. << "The token must be an closing group symbol!";
  639. return closing_token_info.opening_token;
  640. }
  641. auto TokenizedBuffer::HasLeadingWhitespace(Token token) const -> bool {
  642. auto it = TokenIterator(token);
  643. return it == tokens().begin() || GetTokenInfo(*(it - 1)).has_trailing_space;
  644. }
  645. auto TokenizedBuffer::HasTrailingWhitespace(Token token) const -> bool {
  646. return GetTokenInfo(token).has_trailing_space;
  647. }
  648. auto TokenizedBuffer::IsRecoveryToken(Token token) const -> bool {
  649. return GetTokenInfo(token).is_recovery;
  650. }
  651. auto TokenizedBuffer::GetLineNumber(Line line) const -> int {
  652. return line.index_ + 1;
  653. }
  654. auto TokenizedBuffer::GetIndentColumnNumber(Line line) const -> int {
  655. return GetLineInfo(line).indent + 1;
  656. }
  657. auto TokenizedBuffer::GetIdentifierText(Identifier identifier) const
  658. -> llvm::StringRef {
  659. return identifier_infos_[identifier.index_].text;
  660. }
  661. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  662. index = std::max(widths.index, index);
  663. kind = std::max(widths.kind, kind);
  664. column = std::max(widths.column, column);
  665. line = std::max(widths.line, line);
  666. indent = std::max(widths.indent, indent);
  667. }
  668. // Compute the printed width of a number. When numbers are printed in decimal,
  669. // the number of digits needed is is one more than the log-base-10 of the
  670. // value. We handle a value of `zero` explicitly.
  671. //
  672. // This routine requires its argument to be *non-negative*.
  673. static auto ComputeDecimalPrintedWidth(int number) -> int {
  674. CHECK(number >= 0) << "Negative numbers are not supported.";
  675. if (number == 0) {
  676. return 1;
  677. }
  678. return static_cast<int>(std::log10(number)) + 1;
  679. }
  680. auto TokenizedBuffer::GetTokenPrintWidths(Token token) const -> PrintWidths {
  681. PrintWidths widths = {};
  682. widths.index = ComputeDecimalPrintedWidth(token_infos_.size());
  683. widths.kind = GetKind(token).Name().size();
  684. widths.line = ComputeDecimalPrintedWidth(GetLineNumber(token));
  685. widths.column = ComputeDecimalPrintedWidth(GetColumnNumber(token));
  686. widths.indent =
  687. ComputeDecimalPrintedWidth(GetIndentColumnNumber(GetLine(token)));
  688. return widths;
  689. }
  690. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  691. if (tokens().begin() == tokens().end()) {
  692. return;
  693. }
  694. PrintWidths widths = {};
  695. widths.index = ComputeDecimalPrintedWidth((token_infos_.size()));
  696. for (Token token : tokens()) {
  697. widths.Widen(GetTokenPrintWidths(token));
  698. }
  699. for (Token token : tokens()) {
  700. PrintToken(output_stream, token, widths);
  701. output_stream << "\n";
  702. }
  703. }
  704. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  705. Token token) const -> void {
  706. PrintToken(output_stream, token, {});
  707. }
  708. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, Token token,
  709. PrintWidths widths) const -> void {
  710. widths.Widen(GetTokenPrintWidths(token));
  711. int token_index = token.index_;
  712. auto& token_info = GetTokenInfo(token);
  713. llvm::StringRef token_text = GetTokenText(token);
  714. // Output the main chunk using one format string. We have to do the
  715. // justification manually in order to use the dynamically computed widths
  716. // and get the quotes included.
  717. output_stream << llvm::formatv(
  718. "token: { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  719. "spelling: '{5}'",
  720. llvm::format_decimal(token_index, widths.index),
  721. llvm::right_justify(
  722. (llvm::Twine("'") + token_info.kind.Name() + "'").str(),
  723. widths.kind + 2),
  724. llvm::format_decimal(GetLineNumber(token_info.token_line), widths.line),
  725. llvm::format_decimal(GetColumnNumber(token), widths.column),
  726. llvm::format_decimal(GetIndentColumnNumber(token_info.token_line),
  727. widths.indent),
  728. token_text);
  729. switch (token_info.kind) {
  730. case TokenKind::Identifier():
  731. output_stream << ", identifier: " << GetIdentifier(token).index_;
  732. break;
  733. case TokenKind::IntegerLiteral():
  734. output_stream << ", value: `" << GetIntegerLiteral(token) << "`";
  735. break;
  736. case TokenKind::RealLiteral():
  737. output_stream << ", value: `" << GetRealLiteral(token) << "`";
  738. break;
  739. case TokenKind::StringLiteral():
  740. output_stream << ", value: `" << GetStringLiteral(token) << "`";
  741. break;
  742. default:
  743. if (token_info.kind.IsOpeningSymbol()) {
  744. output_stream << ", closing_token: "
  745. << GetMatchedClosingToken(token).index_;
  746. } else if (token_info.kind.IsClosingSymbol()) {
  747. output_stream << ", opening_token: "
  748. << GetMatchedOpeningToken(token).index_;
  749. }
  750. break;
  751. }
  752. if (token_info.has_trailing_space) {
  753. output_stream << ", has_trailing_space: true";
  754. }
  755. if (token_info.is_recovery) {
  756. output_stream << ", recovery: true";
  757. }
  758. output_stream << " }";
  759. }
  760. auto TokenizedBuffer::GetLineInfo(Line line) -> LineInfo& {
  761. return line_infos_[line.index_];
  762. }
  763. auto TokenizedBuffer::GetLineInfo(Line line) const -> const LineInfo& {
  764. return line_infos_[line.index_];
  765. }
  766. auto TokenizedBuffer::AddLine(LineInfo info) -> Line {
  767. line_infos_.push_back(info);
  768. return Line(static_cast<int>(line_infos_.size()) - 1);
  769. }
  770. auto TokenizedBuffer::GetTokenInfo(Token token) -> TokenInfo& {
  771. return token_infos_[token.index_];
  772. }
  773. auto TokenizedBuffer::GetTokenInfo(Token token) const -> const TokenInfo& {
  774. return token_infos_[token.index_];
  775. }
  776. auto TokenizedBuffer::AddToken(TokenInfo info) -> Token {
  777. token_infos_.push_back(info);
  778. return Token(static_cast<int>(token_infos_.size()) - 1);
  779. }
  780. auto TokenizedBuffer::TokenIterator::Print(llvm::raw_ostream& output) const
  781. -> void {
  782. output << token_.index_;
  783. }
  784. auto TokenizedBuffer::SourceBufferLocationTranslator::GetLocation(
  785. const char* loc) -> Diagnostic::Location {
  786. CHECK(StringRefContainsPointer(buffer_->source_->text(), loc))
  787. << "location not within buffer";
  788. int64_t offset = loc - buffer_->source_->text().begin();
  789. // Find the first line starting after the given location. Note that we can't
  790. // inspect `line.length` here because it is not necessarily correct for the
  791. // final line during lexing (but will be correct later for the parse tree).
  792. auto line_it = std::partition_point(
  793. buffer_->line_infos_.begin(), buffer_->line_infos_.end(),
  794. [offset](const LineInfo& line) { return line.start <= offset; });
  795. bool incomplete_line_info = last_line_lexed_to_column_ != nullptr &&
  796. line_it == buffer_->line_infos_.end();
  797. // Step back one line to find the line containing the given position.
  798. CHECK(line_it != buffer_->line_infos_.begin())
  799. << "location precedes the start of the first line";
  800. --line_it;
  801. int line_number = line_it - buffer_->line_infos_.begin();
  802. int column_number = offset - line_it->start;
  803. // We might still be lexing the last line. If so, check to see if there are
  804. // any newline characters between the position we've finished lexing up to
  805. // and the given location.
  806. if (incomplete_line_info && column_number > *last_line_lexed_to_column_) {
  807. column_number = *last_line_lexed_to_column_;
  808. for (int64_t i = line_it->start + *last_line_lexed_to_column_; i != offset;
  809. ++i) {
  810. if (buffer_->source_->text()[i] == '\n') {
  811. ++line_number;
  812. column_number = 0;
  813. } else {
  814. ++column_number;
  815. }
  816. }
  817. }
  818. return {.file_name = buffer_->source_->filename().str(),
  819. .line_number = line_number + 1,
  820. .column_number = column_number + 1};
  821. }
  822. auto TokenizedBuffer::TokenLocationTranslator::GetLocation(Token token)
  823. -> Diagnostic::Location {
  824. // Map the token location into a position within the source buffer.
  825. auto& token_info = buffer_->GetTokenInfo(token);
  826. auto& line_info = buffer_->GetLineInfo(token_info.token_line);
  827. const char* token_start =
  828. buffer_->source_->text().begin() + line_info.start + token_info.column;
  829. // Find the corresponding file location.
  830. // TODO: Should we somehow indicate in the diagnostic location if this token
  831. // is a recovery token that doesn't correspond to the original source?
  832. return SourceBufferLocationTranslator(*buffer_, last_line_lexed_to_column_)
  833. .GetLocation(token_start);
  834. }
  835. } // namespace Carbon