tokenized_buffer.cpp 26 KB

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