tokenized_buffer.cpp 34 KB

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