tokenized_buffer.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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 "lexer/tokenized_buffer.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include <iterator>
  8. #include <string>
  9. #include "lexer/numeric_literal.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/ADT/StringSwitch.h"
  12. #include "llvm/ADT/Twine.h"
  13. #include "llvm/Support/ErrorHandling.h"
  14. #include "llvm/Support/Format.h"
  15. #include "llvm/Support/FormatVariadic.h"
  16. #include "llvm/Support/raw_ostream.h"
  17. namespace Carbon {
  18. struct TrailingComment : SimpleDiagnostic<TrailingComment> {
  19. static constexpr llvm::StringLiteral ShortName = "syntax-comments";
  20. static constexpr llvm::StringLiteral Message =
  21. "Trailing comments are not permitted.";
  22. };
  23. struct NoWhitespaceAfterCommentIntroducer
  24. : SimpleDiagnostic<NoWhitespaceAfterCommentIntroducer> {
  25. static constexpr llvm::StringLiteral ShortName = "syntax-comments";
  26. static constexpr llvm::StringLiteral Message =
  27. "Whitespace is required after '//'.";
  28. };
  29. struct UnmatchedClosing : SimpleDiagnostic<UnmatchedClosing> {
  30. static constexpr llvm::StringLiteral ShortName = "syntax-balanced-delimiters";
  31. static constexpr llvm::StringLiteral Message =
  32. "Closing symbol without a corresponding opening symbol.";
  33. };
  34. struct MismatchedClosing : SimpleDiagnostic<MismatchedClosing> {
  35. static constexpr llvm::StringLiteral ShortName = "syntax-balanced-delimiters";
  36. static constexpr llvm::StringLiteral Message =
  37. "Closing symbol does not match most recent opening symbol.";
  38. };
  39. struct UnrecognizedCharacters : SimpleDiagnostic<UnrecognizedCharacters> {
  40. static constexpr llvm::StringLiteral ShortName =
  41. "syntax-unrecognized-characters";
  42. static constexpr llvm::StringLiteral Message =
  43. "Encountered unrecognized characters while parsing.";
  44. };
  45. // TODO(zygoloid): Update this to match whatever we decide qualifies as
  46. // acceptable whitespace.
  47. static bool isSpace(char c) { return c == ' ' || c == '\n' || c == '\t'; }
  48. // Implementation of the lexer logic itself.
  49. //
  50. // The design is that lexing can loop over the source buffer, consuming it into
  51. // tokens by calling into this API. This class handles the state and breaks down
  52. // the different lexing steps that may be used. It directly updates the provided
  53. // tokenized buffer with the lexed tokens.
  54. class TokenizedBuffer::Lexer {
  55. TokenizedBuffer& buffer;
  56. DiagnosticEmitter& emitter;
  57. Line current_line;
  58. LineInfo* current_line_info;
  59. int current_column = 0;
  60. bool set_indent = false;
  61. llvm::SmallVector<Token, 8> open_groups;
  62. public:
  63. Lexer(TokenizedBuffer& buffer, DiagnosticEmitter& emitter)
  64. : buffer(buffer),
  65. emitter(emitter),
  66. current_line(buffer.AddLine({0, 0, 0})),
  67. current_line_info(&buffer.GetLineInfo(current_line)) {}
  68. // Symbolic result of a lexing action. This indicates whether we successfully
  69. // lexed a token, or whether other lexing actions should be attempted.
  70. //
  71. // While it wraps a simple boolean state, its API both helps make the failures
  72. // more self documenting, and by consuming the actual token constructively
  73. // when one is produced, it helps ensure the correct result is returned.
  74. class LexResult {
  75. bool formed_token;
  76. explicit LexResult(bool formed_token) : formed_token(formed_token) {}
  77. public:
  78. // Consumes (and discard) a valid token to construct a result
  79. // indicating a token has been produced.
  80. LexResult(Token) : LexResult(true) {}
  81. // Returns a result indicating no token was produced.
  82. static LexResult NoMatch() { return LexResult(false); }
  83. // Tests whether a token was produced by the lexing routine, and
  84. // the lexer can continue forming tokens.
  85. explicit operator bool() const { return formed_token; }
  86. };
  87. auto SkipWhitespace(llvm::StringRef& source_text) -> bool {
  88. while (!source_text.empty()) {
  89. // We only support line-oriented commenting and lex comments as-if they
  90. // were whitespace.
  91. if (source_text.startswith("//")) {
  92. // Any comment must be the only non-whitespace on the line.
  93. if (set_indent) {
  94. emitter.EmitError<TrailingComment>();
  95. buffer.has_errors = true;
  96. }
  97. // The introducer '//' must be followed by whitespace or EOF.
  98. if (source_text.size() > 2 && !isSpace(source_text[2])) {
  99. emitter.EmitError<NoWhitespaceAfterCommentIntroducer>();
  100. buffer.has_errors = true;
  101. }
  102. while (!source_text.empty() && source_text.front() != '\n') {
  103. ++current_column;
  104. source_text = source_text.drop_front();
  105. }
  106. if (source_text.empty()) {
  107. break;
  108. }
  109. }
  110. switch (source_text.front()) {
  111. default:
  112. // If we find a non-whitespace character without exhausting the
  113. // buffer, return true to continue lexing.
  114. assert(!isSpace(source_text.front()));
  115. return true;
  116. case '\n':
  117. // New lines are special in order to track line structure.
  118. current_line_info->length = current_column;
  119. // If this is the last character in the source, directly return here
  120. // to avoid creating an empty line.
  121. source_text = source_text.drop_front();
  122. if (source_text.empty()) {
  123. return false;
  124. }
  125. // Otherwise, add a line and set up to continue lexing.
  126. current_line = buffer.AddLine(
  127. {current_line_info->start + current_column + 1, 0, 0});
  128. current_line_info = &buffer.GetLineInfo(current_line);
  129. current_column = 0;
  130. set_indent = false;
  131. continue;
  132. case ' ':
  133. case '\t':
  134. // Skip other forms of whitespace while tracking column.
  135. // FIXME: This obviously needs looooots more work to handle unicode
  136. // whitespace as well as special handling to allow better tokenization
  137. // of operators. This is just a stub to check that our column
  138. // management works.
  139. ++current_column;
  140. source_text = source_text.drop_front();
  141. continue;
  142. }
  143. }
  144. assert(source_text.empty() && "Cannot reach here w/o finishing the text!");
  145. // Update the line length as this is also the end of a line.
  146. current_line_info->length = current_column;
  147. return false;
  148. }
  149. auto LexNumericLiteral(llvm::StringRef& source_text) -> LexResult {
  150. llvm::Optional<NumericLiteralToken> literal =
  151. NumericLiteralToken::Lex(source_text);
  152. if (!literal) {
  153. return LexResult::NoMatch();
  154. }
  155. int int_column = current_column;
  156. int token_size = literal->Text().size();
  157. current_column += token_size;
  158. source_text = source_text.drop_front(token_size);
  159. if (!set_indent) {
  160. current_line_info->indent = int_column;
  161. set_indent = true;
  162. }
  163. NumericLiteralToken::Parser literal_parser(emitter, *literal);
  164. switch (literal_parser.Check()) {
  165. case NumericLiteralToken::Parser::UnrecoverableError: {
  166. auto token = buffer.AddToken({
  167. .kind = TokenKind::Error(),
  168. .token_line = current_line,
  169. .column = int_column,
  170. .error_length = token_size,
  171. });
  172. buffer.has_errors = true;
  173. return token;
  174. }
  175. case NumericLiteralToken::Parser::RecoverableError:
  176. buffer.has_errors = true;
  177. break;
  178. case NumericLiteralToken::Parser::Valid:
  179. break;
  180. }
  181. if (literal_parser.IsInteger()) {
  182. auto token = buffer.AddToken({.kind = TokenKind::IntegerLiteral(),
  183. .token_line = current_line,
  184. .column = int_column});
  185. buffer.GetTokenInfo(token).literal_index =
  186. buffer.literal_int_storage.size();
  187. buffer.literal_int_storage.push_back(literal_parser.GetMantissa());
  188. return token;
  189. } else {
  190. auto token = buffer.AddToken({.kind = TokenKind::RealLiteral(),
  191. .token_line = current_line,
  192. .column = int_column});
  193. buffer.GetTokenInfo(token).literal_index =
  194. buffer.literal_int_storage.size();
  195. buffer.literal_int_storage.push_back(literal_parser.GetMantissa());
  196. buffer.literal_int_storage.push_back(literal_parser.GetExponent());
  197. return token;
  198. }
  199. }
  200. auto LexSymbolToken(llvm::StringRef& source_text) -> LexResult {
  201. TokenKind kind = llvm::StringSwitch<TokenKind>(source_text)
  202. #define CARBON_SYMBOL_TOKEN(Name, Spelling) \
  203. .StartsWith(Spelling, TokenKind::Name())
  204. #include "lexer/token_registry.def"
  205. .Default(TokenKind::Error());
  206. if (kind == TokenKind::Error()) {
  207. return LexResult::NoMatch();
  208. }
  209. if (!set_indent) {
  210. current_line_info->indent = current_column;
  211. set_indent = true;
  212. }
  213. CloseInvalidOpenGroups(kind);
  214. Token token = buffer.AddToken(
  215. {.kind = kind, .token_line = current_line, .column = current_column});
  216. current_column += kind.GetFixedSpelling().size();
  217. source_text = source_text.drop_front(kind.GetFixedSpelling().size());
  218. // Opening symbols just need to be pushed onto our queue of opening groups.
  219. if (kind.IsOpeningSymbol()) {
  220. open_groups.push_back(token);
  221. return token;
  222. }
  223. // Only closing symbols need further special handling.
  224. if (!kind.IsClosingSymbol()) {
  225. return token;
  226. }
  227. TokenInfo& closing_token_info = buffer.GetTokenInfo(token);
  228. // Check that there is a matching opening symbol before we consume this as
  229. // a closing symbol.
  230. if (open_groups.empty()) {
  231. closing_token_info.kind = TokenKind::Error();
  232. closing_token_info.error_length = kind.GetFixedSpelling().size();
  233. buffer.has_errors = true;
  234. emitter.EmitError<UnmatchedClosing>();
  235. // Note that this still returns true as we do consume a symbol.
  236. return token;
  237. }
  238. // Finally can handle a normal closing symbol.
  239. Token opening_token = open_groups.pop_back_val();
  240. TokenInfo& opening_token_info = buffer.GetTokenInfo(opening_token);
  241. opening_token_info.closing_token = token;
  242. closing_token_info.opening_token = opening_token;
  243. return token;
  244. }
  245. // Closes all open groups that cannot remain open across the symbol `K`.
  246. // Users may pass `Error` to close all open groups.
  247. auto CloseInvalidOpenGroups(TokenKind kind) -> void {
  248. if (!kind.IsClosingSymbol() && kind != TokenKind::Error()) {
  249. return;
  250. }
  251. while (!open_groups.empty()) {
  252. Token opening_token = open_groups.back();
  253. TokenKind opening_kind = buffer.GetTokenInfo(opening_token).kind;
  254. if (kind == opening_kind.GetClosingSymbol()) {
  255. return;
  256. }
  257. open_groups.pop_back();
  258. buffer.has_errors = true;
  259. emitter.EmitError<MismatchedClosing>();
  260. // TODO: do a smarter backwards scan for where to put the closing
  261. // token.
  262. Token closing_token =
  263. buffer.AddToken({.kind = opening_kind.GetClosingSymbol(),
  264. .is_recovery = true,
  265. .token_line = current_line,
  266. .column = current_column});
  267. TokenInfo& opening_token_info = buffer.GetTokenInfo(opening_token);
  268. TokenInfo& closing_token_info = buffer.GetTokenInfo(closing_token);
  269. opening_token_info.closing_token = closing_token;
  270. closing_token_info.opening_token = opening_token;
  271. }
  272. }
  273. auto GetOrCreateIdentifier(llvm::StringRef text) -> Identifier {
  274. auto insert_result = buffer.identifier_map.insert(
  275. {text, Identifier(buffer.identifier_infos.size())});
  276. if (insert_result.second) {
  277. buffer.identifier_infos.push_back({text});
  278. }
  279. return insert_result.first->second;
  280. }
  281. auto LexKeywordOrIdentifier(llvm::StringRef& source_text) -> LexResult {
  282. if (!llvm::isAlpha(source_text.front()) && source_text.front() != '_') {
  283. return LexResult::NoMatch();
  284. }
  285. if (!set_indent) {
  286. current_line_info->indent = current_column;
  287. set_indent = true;
  288. }
  289. // Take the valid characters off the front of the source buffer.
  290. llvm::StringRef identifier_text = source_text.take_while(
  291. [](char c) { return llvm::isAlnum(c) || c == '_'; });
  292. assert(!identifier_text.empty() && "Must have at least one character!");
  293. int identifier_column = current_column;
  294. current_column += identifier_text.size();
  295. source_text = source_text.drop_front(identifier_text.size());
  296. // Check if the text matches a keyword token, and if so use that.
  297. TokenKind kind = llvm::StringSwitch<TokenKind>(identifier_text)
  298. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, TokenKind::Name())
  299. #include "lexer/token_registry.def"
  300. .Default(TokenKind::Error());
  301. if (kind != TokenKind::Error()) {
  302. return buffer.AddToken({.kind = kind,
  303. .token_line = current_line,
  304. .column = identifier_column});
  305. }
  306. // Otherwise we have a generic identifier.
  307. return buffer.AddToken({.kind = TokenKind::Identifier(),
  308. .token_line = current_line,
  309. .column = identifier_column,
  310. .id = GetOrCreateIdentifier(identifier_text)});
  311. }
  312. auto LexError(llvm::StringRef& source_text) -> LexResult {
  313. llvm::StringRef error_text = source_text.take_while([](char c) {
  314. if (llvm::isAlnum(c)) {
  315. return false;
  316. }
  317. switch (c) {
  318. case '_':
  319. case '\t':
  320. case '\n':
  321. return false;
  322. }
  323. return llvm::StringSwitch<bool>(llvm::StringRef(&c, 1))
  324. #define CARBON_SYMBOL_TOKEN(Name, Spelling) .StartsWith(Spelling, false)
  325. #include "lexer/token_registry.def"
  326. .Default(true);
  327. });
  328. if (error_text.empty()) {
  329. // TODO: Reimplement this to use the lexer properly. In the meantime,
  330. // guarantee that we eat at least one byte.
  331. error_text = source_text.take_front(1);
  332. }
  333. // Longer errors get to be two tokens.
  334. error_text = error_text.substr(0, std::numeric_limits<int32_t>::max());
  335. auto token = buffer.AddToken(
  336. {.kind = TokenKind::Error(),
  337. .token_line = current_line,
  338. .column = current_column,
  339. .error_length = static_cast<int32_t>(error_text.size())});
  340. // TODO: #19 - Need to convert to the diagnostics library.
  341. llvm::errs() << "ERROR: Line " << buffer.GetLineNumber(token) << ", Column "
  342. << buffer.GetColumnNumber(token)
  343. << ": Unrecognized characters!\n";
  344. current_column += error_text.size();
  345. source_text = source_text.drop_front(error_text.size());
  346. buffer.has_errors = true;
  347. return token;
  348. }
  349. };
  350. auto TokenizedBuffer::Lex(SourceBuffer& source, DiagnosticEmitter& emitter)
  351. -> TokenizedBuffer {
  352. TokenizedBuffer buffer(source);
  353. Lexer lexer(buffer, emitter);
  354. llvm::StringRef source_text = source.Text();
  355. while (lexer.SkipWhitespace(source_text)) {
  356. // Each time we find non-whitespace characters, try each kind of token we
  357. // support lexing, from simplest to most complex.
  358. Lexer::LexResult result = lexer.LexSymbolToken(source_text);
  359. if (!result) {
  360. result = lexer.LexKeywordOrIdentifier(source_text);
  361. }
  362. if (!result) {
  363. result = lexer.LexNumericLiteral(source_text);
  364. }
  365. if (!result) {
  366. result = lexer.LexError(source_text);
  367. }
  368. assert(result && "No token was lexed.");
  369. }
  370. lexer.CloseInvalidOpenGroups(TokenKind::Error());
  371. return buffer;
  372. }
  373. auto TokenizedBuffer::GetKind(Token token) const -> TokenKind {
  374. return GetTokenInfo(token).kind;
  375. }
  376. auto TokenizedBuffer::GetLine(Token token) const -> Line {
  377. return GetTokenInfo(token).token_line;
  378. }
  379. auto TokenizedBuffer::GetLineNumber(Token token) const -> int {
  380. return GetLineNumber(GetLine(token));
  381. }
  382. auto TokenizedBuffer::GetColumnNumber(Token token) const -> int {
  383. return GetTokenInfo(token).column + 1;
  384. }
  385. auto TokenizedBuffer::GetTokenText(Token token) const -> llvm::StringRef {
  386. auto& token_info = GetTokenInfo(token);
  387. llvm::StringRef fixed_spelling = token_info.kind.GetFixedSpelling();
  388. if (!fixed_spelling.empty()) {
  389. return fixed_spelling;
  390. }
  391. if (token_info.kind == TokenKind::Error()) {
  392. auto& line_info = GetLineInfo(token_info.token_line);
  393. int64_t token_start = line_info.start + token_info.column;
  394. return source->Text().substr(token_start, token_info.error_length);
  395. }
  396. // Refer back to the source text to preserve oddities like radix or digit
  397. // separators the author included.
  398. if (token_info.kind == TokenKind::IntegerLiteral() ||
  399. token_info.kind == TokenKind::RealLiteral()) {
  400. auto& line_info = GetLineInfo(token_info.token_line);
  401. int64_t token_start = line_info.start + token_info.column;
  402. llvm::Optional<NumericLiteralToken> relexed_token =
  403. NumericLiteralToken::Lex(source->Text().substr(token_start));
  404. assert(relexed_token && "Could not reform numeric literal token.");
  405. return relexed_token->Text();
  406. }
  407. assert(token_info.kind == TokenKind::Identifier() &&
  408. "Only identifiers have stored text!");
  409. return GetIdentifierText(token_info.id);
  410. }
  411. auto TokenizedBuffer::GetIdentifier(Token token) const -> Identifier {
  412. auto& token_info = GetTokenInfo(token);
  413. assert(token_info.kind == TokenKind::Identifier() &&
  414. "The token must be an identifier!");
  415. return token_info.id;
  416. }
  417. auto TokenizedBuffer::GetIntegerLiteral(Token token) const
  418. -> const llvm::APInt& {
  419. auto& token_info = GetTokenInfo(token);
  420. assert(token_info.kind == TokenKind::IntegerLiteral() &&
  421. "The token must be an integer literal!");
  422. return literal_int_storage[token_info.literal_index];
  423. }
  424. auto TokenizedBuffer::GetRealLiteral(Token token) const -> RealLiteralValue {
  425. auto& token_info = GetTokenInfo(token);
  426. assert(token_info.kind == TokenKind::RealLiteral() &&
  427. "The token must be a real literal!");
  428. // Note that every real literal is at least three characters long, so we can
  429. // safely look at the second character to determine whether we have a decimal
  430. // or hexadecimal literal.
  431. auto& line_info = GetLineInfo(token_info.token_line);
  432. int64_t token_start = line_info.start + token_info.column;
  433. char second_char = source->Text()[token_start + 1];
  434. bool is_decimal = second_char != 'x' && second_char != 'b';
  435. return RealLiteralValue(this, token_info.literal_index, is_decimal);
  436. }
  437. auto TokenizedBuffer::GetMatchedClosingToken(Token opening_token) const
  438. -> Token {
  439. auto& opening_token_info = GetTokenInfo(opening_token);
  440. assert(opening_token_info.kind.IsOpeningSymbol() &&
  441. "The token must be an opening group symbol!");
  442. return opening_token_info.closing_token;
  443. }
  444. auto TokenizedBuffer::GetMatchedOpeningToken(Token closing_token) const
  445. -> Token {
  446. auto& closing_token_info = GetTokenInfo(closing_token);
  447. assert(closing_token_info.kind.IsClosingSymbol() &&
  448. "The token must be an closing group symbol!");
  449. return closing_token_info.opening_token;
  450. }
  451. auto TokenizedBuffer::IsRecoveryToken(Token token) const -> bool {
  452. return GetTokenInfo(token).is_recovery;
  453. }
  454. auto TokenizedBuffer::GetLineNumber(Line line) const -> int {
  455. return line.index + 1;
  456. }
  457. auto TokenizedBuffer::GetIndentColumnNumber(Line line) const -> int {
  458. return GetLineInfo(line).indent + 1;
  459. }
  460. auto TokenizedBuffer::GetIdentifierText(Identifier identifier) const
  461. -> llvm::StringRef {
  462. return identifier_infos[identifier.index].text;
  463. }
  464. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  465. index = std::max(widths.index, index);
  466. kind = std::max(widths.kind, kind);
  467. column = std::max(widths.column, column);
  468. line = std::max(widths.line, line);
  469. indent = std::max(widths.indent, indent);
  470. }
  471. // Compute the printed width of a number. When numbers are printed in decimal,
  472. // the number of digits needed is is one more than the log-base-10 of the value.
  473. // We handle a value of `zero` explicitly.
  474. //
  475. // This routine requires its argument to be *non-negative*.
  476. static auto ComputeDecimalPrintedWidth(int number) -> int {
  477. assert(number >= 0 && "Negative numbers are not supported.");
  478. if (number == 0) {
  479. return 1;
  480. }
  481. return static_cast<int>(std::log10(number)) + 1;
  482. }
  483. auto TokenizedBuffer::GetTokenPrintWidths(Token token) const -> PrintWidths {
  484. PrintWidths widths = {};
  485. widths.index = ComputeDecimalPrintedWidth(token_infos.size());
  486. widths.kind = GetKind(token).Name().size();
  487. widths.line = ComputeDecimalPrintedWidth(GetLineNumber(token));
  488. widths.column = ComputeDecimalPrintedWidth(GetColumnNumber(token));
  489. widths.indent =
  490. ComputeDecimalPrintedWidth(GetIndentColumnNumber(GetLine(token)));
  491. return widths;
  492. }
  493. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  494. if (Tokens().begin() == Tokens().end()) {
  495. return;
  496. }
  497. PrintWidths widths = {};
  498. widths.index = ComputeDecimalPrintedWidth((token_infos.size()));
  499. for (Token token : Tokens()) {
  500. widths.Widen(GetTokenPrintWidths(token));
  501. }
  502. for (Token token : Tokens()) {
  503. PrintToken(output_stream, token, widths);
  504. output_stream << "\n";
  505. }
  506. }
  507. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  508. Token token) const -> void {
  509. PrintToken(output_stream, token, {});
  510. }
  511. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, Token token,
  512. PrintWidths widths) const -> void {
  513. widths.Widen(GetTokenPrintWidths(token));
  514. int token_index = token.index;
  515. auto& token_info = GetTokenInfo(token);
  516. llvm::StringRef token_text = GetTokenText(token);
  517. // Output the main chunk using one format string. We have to do the
  518. // justification manually in order to use the dynamically computed widths
  519. // and get the quotes included.
  520. output_stream << llvm::formatv(
  521. "token: { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  522. "spelling: '{5}'",
  523. llvm::format_decimal(token_index, widths.index),
  524. llvm::right_justify(
  525. (llvm::Twine("'") + token_info.kind.Name() + "'").str(),
  526. widths.kind + 2),
  527. llvm::format_decimal(GetLineNumber(token_info.token_line), widths.line),
  528. llvm::format_decimal(GetColumnNumber(token), widths.column),
  529. llvm::format_decimal(GetIndentColumnNumber(token_info.token_line),
  530. widths.indent),
  531. token_text);
  532. if (token_info.kind == TokenKind::Identifier()) {
  533. output_stream << ", identifier: " << GetIdentifier(token).index;
  534. } else if (token_info.kind.IsOpeningSymbol()) {
  535. output_stream << ", closing_token: " << GetMatchedClosingToken(token).index;
  536. } else if (token_info.kind.IsClosingSymbol()) {
  537. output_stream << ", opening_token: " << GetMatchedOpeningToken(token).index;
  538. }
  539. if (token_info.is_recovery) {
  540. output_stream << ", recovery: true";
  541. }
  542. output_stream << " }";
  543. }
  544. auto TokenizedBuffer::GetLineInfo(Line line) -> LineInfo& {
  545. return line_infos[line.index];
  546. }
  547. auto TokenizedBuffer::GetLineInfo(Line line) const -> const LineInfo& {
  548. return line_infos[line.index];
  549. }
  550. auto TokenizedBuffer::AddLine(LineInfo info) -> Line {
  551. line_infos.push_back(info);
  552. return Line(static_cast<int>(line_infos.size()) - 1);
  553. }
  554. auto TokenizedBuffer::GetTokenInfo(Token token) -> TokenInfo& {
  555. return token_infos[token.index];
  556. }
  557. auto TokenizedBuffer::GetTokenInfo(Token token) const -> const TokenInfo& {
  558. return token_infos[token.index];
  559. }
  560. auto TokenizedBuffer::AddToken(TokenInfo info) -> Token {
  561. token_infos.push_back(info);
  562. return Token(static_cast<int>(token_infos.size()) - 1);
  563. }
  564. } // namespace Carbon