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