tokenized_buffer.cpp 33 KB

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