tokenized_buffer.cpp 26 KB

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