tokenized_buffer.cpp 33 KB

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