tokenized_buffer.cpp 34 KB

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