tokenized_buffer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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 <bitset>
  7. #include <cmath>
  8. #include <iterator>
  9. #include <string>
  10. #include "llvm/ADT/StringExtras.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. static auto TakeLeadingIntegerLiteral(llvm::StringRef source_text)
  20. -> llvm::StringRef {
  21. if (source_text.empty() || !llvm::isDigit(source_text.front()))
  22. return llvm::StringRef();
  23. // Greedily consume all following characters that might be part of an integer
  24. // literal. This allows us to produce better diagnostics on invalid literals.
  25. //
  26. // TODO(zygoloid): Update lexical rules to specify that an integer literal
  27. // cannot be immediately followed by another integer literal or a word.
  28. return source_text.take_while(
  29. [](char c) { return llvm::isAlnum(c) || c == '_'; });
  30. }
  31. struct 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. struct Substitutions {};
  36. static auto Format(const Substitutions&) -> std::string {
  37. return Message.str();
  38. }
  39. };
  40. struct 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. struct Substitutions {};
  45. static auto Format(const Substitutions&) -> std::string {
  46. return Message.str();
  47. }
  48. };
  49. struct EmptyDigitSequence {
  50. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  51. static constexpr llvm::StringLiteral Message =
  52. "Empty digit sequence in numeric literal.";
  53. struct Substitutions {};
  54. static auto Format(const Substitutions&) -> std::string {
  55. return Message.str();
  56. }
  57. };
  58. struct InvalidDigit {
  59. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  60. struct Substitutions {
  61. char digit;
  62. unsigned radix;
  63. };
  64. static auto Format(const Substitutions& subst) -> std::string {
  65. // TODO: Switch Format to using raw_ostream so we can easily use
  66. // llvm::format here.
  67. llvm::StringRef digit_str(&subst.digit, 1);
  68. return (llvm::Twine("Invalid digit '") + digit_str + "' in " +
  69. (subst.radix == 2 ? "binary"
  70. : subst.radix == 16 ? "hexadecimal" : "decimal") +
  71. " numeric literal.")
  72. .str();
  73. }
  74. };
  75. struct InvalidDigitSeparator {
  76. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  77. static constexpr llvm::StringLiteral Message =
  78. "Misplaced digit separator in numeric literal.";
  79. struct Substitutions {};
  80. static auto Format(const Substitutions&) -> std::string {
  81. return Message.str();
  82. }
  83. };
  84. struct IrregularDigitSeparators {
  85. static constexpr llvm::StringLiteral ShortName =
  86. "syntax-irregular-digit-separators";
  87. struct Substitutions {
  88. unsigned radix;
  89. };
  90. static auto Format(const Substitutions& subst) -> std::string {
  91. assert((subst.radix == 10 || subst.radix == 16) && "unexpected radix");
  92. return (llvm::Twine("Digit separators in ") +
  93. (subst.radix == 10 ? "decimal" : "hexadecimal") +
  94. " should appear every " + (subst.radix == 10 ? "3" : "4") +
  95. " characters from the right.")
  96. .str();
  97. }
  98. };
  99. struct UnknownBaseSpecifier {
  100. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  101. static constexpr llvm::StringLiteral Message =
  102. "Unknown base specifier in numeric literal.";
  103. struct Substitutions {};
  104. static auto Format(const Substitutions&) -> std::string {
  105. return Message.str();
  106. }
  107. };
  108. struct UnrecognizedCharacters {
  109. static constexpr llvm::StringLiteral ShortName =
  110. "syntax-unrecognized-characters";
  111. static constexpr llvm::StringLiteral Message =
  112. "Encountered unrecognized characters while parsing.";
  113. struct Substitutions {};
  114. static auto Format(const Substitutions&) -> std::string {
  115. return Message.str();
  116. }
  117. };
  118. // Implementation of the lexer logic itself.
  119. //
  120. // The design is that lexing can loop over the source buffer, consuming it into
  121. // tokens by calling into this API. This class handles the state and breaks down
  122. // the different lexing steps that may be used. It directly updates the provided
  123. // tokenized buffer with the lexed tokens.
  124. class TokenizedBuffer::Lexer {
  125. TokenizedBuffer& buffer;
  126. DiagnosticEmitter& emitter;
  127. Line current_line;
  128. LineInfo* current_line_info;
  129. int current_column = 0;
  130. bool set_indent = false;
  131. llvm::SmallVector<Token, 8> open_groups;
  132. public:
  133. Lexer(TokenizedBuffer& buffer, DiagnosticEmitter& emitter)
  134. : buffer(buffer),
  135. emitter(emitter),
  136. current_line(buffer.AddLine({0, 0, 0})),
  137. current_line_info(&buffer.GetLineInfo(current_line)) {}
  138. auto SkipWhitespace(llvm::StringRef& source_text) -> bool {
  139. while (!source_text.empty()) {
  140. // We only support line-oriented commenting and lex comments as-if they
  141. // were whitespace. Any comment must be the only non-whitespace on the
  142. // line.
  143. if (source_text.startswith("//") && !set_indent) {
  144. // Check if the comment has a special starting sequence of three slashes
  145. // followed by a space. This represents a documentation comment that is
  146. // preserved as a token in the buffer. When parsing, these comments will
  147. // only be accepted in specific parts of the grammar and will be
  148. // associated with the parsed constructs as structure documentation. All
  149. // other comments are simply treated as whitespace.
  150. if (source_text.startswith("///")) {
  151. current_line_info->indent = current_column;
  152. set_indent = true;
  153. buffer.AddToken({.kind = TokenKind::DocComment(),
  154. .token_line = current_line,
  155. .column = current_column});
  156. }
  157. while (!source_text.empty() && source_text.front() != '\n') {
  158. ++current_column;
  159. source_text = source_text.drop_front();
  160. }
  161. if (source_text.empty()) {
  162. break;
  163. }
  164. }
  165. switch (source_text.front()) {
  166. default:
  167. // If we find a non-whitespace character without exhausting the
  168. // buffer, return true to continue lexing.
  169. return true;
  170. case '\n':
  171. // New lines are special in order to track line structure.
  172. current_line_info->length = current_column;
  173. // If this is the last character in the source, directly return here
  174. // to avoid creating an empty line.
  175. source_text = source_text.drop_front();
  176. if (source_text.empty()) {
  177. return false;
  178. }
  179. // Otherwise, add a line and set up to continue lexing.
  180. current_line = buffer.AddLine(
  181. {current_line_info->start + current_column + 1, 0, 0});
  182. current_line_info = &buffer.GetLineInfo(current_line);
  183. current_column = 0;
  184. set_indent = false;
  185. continue;
  186. case ' ':
  187. case '\t':
  188. // Skip other forms of whitespace while tracking column.
  189. // FIXME: This obviously needs looooots more work to handle unicode
  190. // whitespace as well as special handling to allow better tokenization
  191. // of operators. This is just a stub to check that our column
  192. // management works.
  193. ++current_column;
  194. source_text = source_text.drop_front();
  195. continue;
  196. }
  197. }
  198. assert(source_text.empty() && "Cannot reach here w/o finishing the text!");
  199. // Update the line length as this is also the end of a line.
  200. current_line_info->length = current_column;
  201. return false;
  202. }
  203. auto CheckDigitSeparatorPlacement(llvm::StringRef text, unsigned radix,
  204. unsigned num_digit_separators) {
  205. assert((radix == 10 || radix == 16) &&
  206. "unexpected radix for digit separator checks");
  207. assert(std::count(text.begin(), text.end(), '_') == num_digit_separators &&
  208. "given wrong number of digit separators");
  209. auto diagnose_irregular_digit_separators = [&] {
  210. emitter.EmitError<IrregularDigitSeparators>(
  211. [&](IrregularDigitSeparators::Substitutions& subst) {
  212. subst.radix = radix;
  213. });
  214. buffer.has_errors = true;
  215. };
  216. // For decimal and hexadecimal digit sequences, digit separators must form
  217. // groups of 3 or 4 digits (4 or 5 characters), respectively.
  218. unsigned stride = (radix == 10 ? 4 : 5);
  219. unsigned remaining_digit_separators = num_digit_separators;
  220. for (auto pos = text.end(); pos - text.begin() >= stride; /*in loop*/) {
  221. pos -= stride;
  222. if (*pos != '_')
  223. return diagnose_irregular_digit_separators();
  224. --remaining_digit_separators;
  225. }
  226. // Check there weren't any other digit separators.
  227. if (remaining_digit_separators)
  228. diagnose_irregular_digit_separators();
  229. };
  230. struct CheckDigitSequenceResult {
  231. bool ok;
  232. bool has_digit_separators = false;
  233. };
  234. auto CheckDigitSequence(llvm::StringRef text, unsigned radix)
  235. -> CheckDigitSequenceResult {
  236. assert((radix == 2 || radix == 10 || radix == 16) && "unknown radix");
  237. if (text.empty()) {
  238. emitter.EmitError<EmptyDigitSequence>(
  239. [&](EmptyDigitSequence::Substitutions&) {});
  240. return {.ok = false};
  241. }
  242. std::bitset<256> valid_digits;
  243. if (radix == 2) {
  244. for (char c : "01")
  245. valid_digits[static_cast<unsigned char>(c)] = true;
  246. } else if (radix == 10) {
  247. for (char c : "0123456789")
  248. valid_digits[static_cast<unsigned char>(c)] = true;
  249. } else {
  250. for (char c : "0123456789ABCDEF")
  251. valid_digits[static_cast<unsigned char>(c)] = true;
  252. }
  253. unsigned num_digit_separators = 0;
  254. for (std::size_t i = 0, n = text.size(); i != n; ++i) {
  255. char c = text[i];
  256. if (valid_digits[static_cast<unsigned char>(c)]) {
  257. continue;
  258. }
  259. if (c == '_') {
  260. // A digit separator cannot appear at the start of a digit sequence,
  261. // next to another digit separator, or at the end.
  262. if (i == 0 || text[i - 1] == '_' || i + 1 == n) {
  263. emitter.EmitError<InvalidDigitSeparator>(
  264. [&](InvalidDigitSeparator::Substitutions&) {});
  265. buffer.has_errors = true;
  266. }
  267. ++num_digit_separators;
  268. continue;
  269. }
  270. emitter.EmitError<InvalidDigit>([&](InvalidDigit::Substitutions& subst) {
  271. subst.digit = c;
  272. subst.radix = radix;
  273. });
  274. return {.ok = false};
  275. }
  276. // Check that digit separators occur in exactly the expected positions.
  277. if (num_digit_separators && radix != 2)
  278. CheckDigitSeparatorPlacement(text, radix, num_digit_separators);
  279. return {.ok = true, .has_digit_separators = (num_digit_separators != 0)};
  280. }
  281. auto LexIntegerLiteral(llvm::StringRef& source_text) -> bool {
  282. llvm::StringRef int_text = TakeLeadingIntegerLiteral(source_text);
  283. if (int_text.empty()) {
  284. return false;
  285. }
  286. int int_column = current_column;
  287. current_column += int_text.size();
  288. source_text = source_text.drop_front(int_text.size());
  289. if (!set_indent) {
  290. current_line_info->indent = int_column;
  291. set_indent = true;
  292. }
  293. auto add_error_token_and_continue_lexing = [&] {
  294. buffer.AddToken({
  295. .kind = TokenKind::Error(),
  296. .token_line = current_line,
  297. .column = int_column,
  298. .error_length = static_cast<int32_t>(int_text.size()),
  299. });
  300. buffer.has_errors = true;
  301. // Indicate to the caller that we consumed a token.
  302. return true;
  303. };
  304. unsigned radix = 10;
  305. llvm::StringRef digits = int_text;
  306. if (int_text.size() >= 2 && int_text[0] == '0') {
  307. if (int_text[1] == 'x') {
  308. radix = 16;
  309. digits = digits.drop_front(2);
  310. } else if (int_text[1] == 'b') {
  311. radix = 2;
  312. digits = digits.drop_front(2);
  313. } else {
  314. emitter.EmitError<UnknownBaseSpecifier>(
  315. [&](UnknownBaseSpecifier::Substitutions& subst) {});
  316. return add_error_token_and_continue_lexing();
  317. }
  318. }
  319. llvm::APInt int_value;
  320. auto result = CheckDigitSequence(digits, radix);
  321. if (!result.ok) {
  322. return add_error_token_and_continue_lexing();
  323. }
  324. if (result.has_digit_separators) {
  325. // TODO(zygoloid): Avoid the memory allocation here.
  326. std::string cleaned;
  327. cleaned.reserve(digits.size());
  328. std::remove_copy_if(digits.begin(), digits.end(),
  329. std::back_inserter(cleaned),
  330. [](char c) { return c == '_'; });
  331. if (llvm::StringRef(cleaned).getAsInteger(radix, int_value)) {
  332. llvm_unreachable("should never fail");
  333. }
  334. } else {
  335. if (digits.getAsInteger(radix, int_value)) {
  336. llvm_unreachable("should never fail");
  337. }
  338. }
  339. auto token = buffer.AddToken({.kind = TokenKind::IntegerLiteral(),
  340. .token_line = current_line,
  341. .column = int_column});
  342. buffer.GetTokenInfo(token).literal_index = buffer.int_literals.size();
  343. buffer.int_literals.push_back(std::move(int_value));
  344. return true;
  345. }
  346. auto LexSymbolToken(llvm::StringRef& source_text) -> bool {
  347. TokenKind kind = llvm::StringSwitch<TokenKind>(source_text)
  348. #define CARBON_SYMBOL_TOKEN(Name, Spelling) \
  349. .StartsWith(Spelling, TokenKind::Name())
  350. #include "lexer/token_registry.def"
  351. .Default(TokenKind::Error());
  352. if (kind == TokenKind::Error()) {
  353. return false;
  354. }
  355. if (!set_indent) {
  356. current_line_info->indent = current_column;
  357. set_indent = true;
  358. }
  359. CloseInvalidOpenGroups(kind);
  360. Token token = buffer.AddToken(
  361. {.kind = kind, .token_line = current_line, .column = current_column});
  362. current_column += kind.GetFixedSpelling().size();
  363. source_text = source_text.drop_front(kind.GetFixedSpelling().size());
  364. // Opening symbols just need to be pushed onto our queue of opening groups.
  365. if (kind.IsOpeningSymbol()) {
  366. open_groups.push_back(token);
  367. return true;
  368. }
  369. // Only closing symbols need further special handling.
  370. if (!kind.IsClosingSymbol()) {
  371. return true;
  372. }
  373. TokenInfo& closing_token_info = buffer.GetTokenInfo(token);
  374. // Check that there is a matching opening symbol before we consume this as
  375. // a closing symbol.
  376. if (open_groups.empty()) {
  377. closing_token_info.kind = TokenKind::Error();
  378. closing_token_info.error_length = kind.GetFixedSpelling().size();
  379. buffer.has_errors = true;
  380. emitter.EmitError<UnmatchedClosing>(
  381. [](UnmatchedClosing::Substitutions&) {});
  382. // Note that this still returns true as we do consume a symbol.
  383. return true;
  384. }
  385. // Finally can handle a normal closing symbol.
  386. Token opening_token = open_groups.pop_back_val();
  387. TokenInfo& opening_token_info = buffer.GetTokenInfo(opening_token);
  388. opening_token_info.closing_token = token;
  389. closing_token_info.opening_token = opening_token;
  390. return true;
  391. }
  392. // Closes all open groups that cannot remain open across the symbol `K`.
  393. // Users may pass `Error` to close all open groups.
  394. auto CloseInvalidOpenGroups(TokenKind kind) -> void {
  395. if (!kind.IsClosingSymbol() && kind != TokenKind::Error()) {
  396. return;
  397. }
  398. while (!open_groups.empty()) {
  399. Token opening_token = open_groups.back();
  400. TokenKind opening_kind = buffer.GetTokenInfo(opening_token).kind;
  401. if (kind == opening_kind.GetClosingSymbol()) {
  402. return;
  403. }
  404. open_groups.pop_back();
  405. buffer.has_errors = true;
  406. emitter.EmitError<MismatchedClosing>(
  407. [](MismatchedClosing::Substitutions&) {});
  408. // TODO: do a smarter backwards scan for where to put the closing
  409. // token.
  410. Token closing_token =
  411. buffer.AddToken({.kind = opening_kind.GetClosingSymbol(),
  412. .is_recovery = true,
  413. .token_line = current_line,
  414. .column = current_column});
  415. TokenInfo& opening_token_info = buffer.GetTokenInfo(opening_token);
  416. TokenInfo& closing_token_info = buffer.GetTokenInfo(closing_token);
  417. opening_token_info.closing_token = closing_token;
  418. closing_token_info.opening_token = opening_token;
  419. }
  420. }
  421. auto GetOrCreateIdentifier(llvm::StringRef text) -> Identifier {
  422. auto insert_result = buffer.identifier_map.insert(
  423. {text, Identifier(buffer.identifier_infos.size())});
  424. if (insert_result.second) {
  425. buffer.identifier_infos.push_back({text});
  426. }
  427. return insert_result.first->second;
  428. }
  429. auto LexKeywordOrIdentifier(llvm::StringRef& source_text) -> bool {
  430. if (!llvm::isAlpha(source_text.front()) && source_text.front() != '_') {
  431. return false;
  432. }
  433. if (!set_indent) {
  434. current_line_info->indent = current_column;
  435. set_indent = true;
  436. }
  437. // Take the valid characters off the front of the source buffer.
  438. llvm::StringRef identifier_text = source_text.take_while(
  439. [](char c) { return llvm::isAlnum(c) || c == '_'; });
  440. assert(!identifier_text.empty() && "Must have at least one character!");
  441. int identifier_column = current_column;
  442. current_column += identifier_text.size();
  443. source_text = source_text.drop_front(identifier_text.size());
  444. // Check if the text matches a keyword token, and if so use that.
  445. TokenKind kind = llvm::StringSwitch<TokenKind>(identifier_text)
  446. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, TokenKind::Name())
  447. #include "lexer/token_registry.def"
  448. .Default(TokenKind::Error());
  449. if (kind != TokenKind::Error()) {
  450. buffer.AddToken({.kind = kind,
  451. .token_line = current_line,
  452. .column = identifier_column});
  453. return true;
  454. }
  455. // Otherwise we have a generic identifier.
  456. buffer.AddToken({.kind = TokenKind::Identifier(),
  457. .token_line = current_line,
  458. .column = identifier_column,
  459. .id = GetOrCreateIdentifier(identifier_text)});
  460. return true;
  461. }
  462. auto LexError(llvm::StringRef& source_text) -> void {
  463. llvm::StringRef error_text = source_text.take_while([](char c) {
  464. if (llvm::isAlnum(c)) {
  465. return false;
  466. }
  467. switch (c) {
  468. case '_':
  469. case '\t':
  470. case '\n':
  471. return false;
  472. }
  473. return llvm::StringSwitch<bool>(llvm::StringRef(&c, 1))
  474. #define CARBON_SYMBOL_TOKEN(Name, Spelling) .StartsWith(Spelling, false)
  475. #include "lexer/token_registry.def"
  476. .Default(true);
  477. });
  478. if (error_text.empty()) {
  479. // TODO: Reimplement this to use the lexer properly. In the meantime,
  480. // guarantee that we eat at least one byte.
  481. error_text = source_text.take_front(1);
  482. }
  483. // Longer errors get to be two tokens.
  484. error_text = error_text.substr(0, std::numeric_limits<int32_t>::max());
  485. auto token = buffer.AddToken(
  486. {.kind = TokenKind::Error(),
  487. .token_line = current_line,
  488. .column = current_column,
  489. .error_length = static_cast<int32_t>(error_text.size())});
  490. // TODO: #19 - Need to convert to the diagnostics library.
  491. llvm::errs() << "ERROR: Line " << buffer.GetLineNumber(token) << ", Column "
  492. << buffer.GetColumnNumber(token)
  493. << ": Unrecognized characters!\n";
  494. current_column += error_text.size();
  495. source_text = source_text.drop_front(error_text.size());
  496. buffer.has_errors = true;
  497. }
  498. };
  499. auto TokenizedBuffer::Lex(SourceBuffer& source, DiagnosticEmitter& emitter)
  500. -> TokenizedBuffer {
  501. TokenizedBuffer buffer(source);
  502. Lexer lexer(buffer, emitter);
  503. llvm::StringRef source_text = source.Text();
  504. while (lexer.SkipWhitespace(source_text)) {
  505. // Each time we find non-whitespace characters, try each kind of token we
  506. // support lexing, from simplest to most complex.
  507. if (lexer.LexSymbolToken(source_text)) {
  508. continue;
  509. }
  510. if (lexer.LexKeywordOrIdentifier(source_text)) {
  511. continue;
  512. }
  513. if (lexer.LexIntegerLiteral(source_text)) {
  514. continue;
  515. }
  516. lexer.LexError(source_text);
  517. }
  518. lexer.CloseInvalidOpenGroups(TokenKind::Error());
  519. return buffer;
  520. }
  521. auto TokenizedBuffer::GetKind(Token token) const -> TokenKind {
  522. return GetTokenInfo(token).kind;
  523. }
  524. auto TokenizedBuffer::GetLine(Token token) const -> Line {
  525. return GetTokenInfo(token).token_line;
  526. }
  527. auto TokenizedBuffer::GetLineNumber(Token token) const -> int {
  528. return GetLineNumber(GetLine(token));
  529. }
  530. auto TokenizedBuffer::GetColumnNumber(Token token) const -> int {
  531. return GetTokenInfo(token).column + 1;
  532. }
  533. auto TokenizedBuffer::GetTokenText(Token token) const -> llvm::StringRef {
  534. auto& token_info = GetTokenInfo(token);
  535. llvm::StringRef fixed_spelling = token_info.kind.GetFixedSpelling();
  536. if (!fixed_spelling.empty()) {
  537. return fixed_spelling;
  538. }
  539. if (token_info.kind == TokenKind::Error()) {
  540. auto& line_info = GetLineInfo(token_info.token_line);
  541. int64_t token_start = line_info.start + token_info.column;
  542. return source->Text().substr(token_start, token_info.error_length);
  543. }
  544. // Documentation comment tokens refer back to the source text.
  545. if (token_info.kind == TokenKind::DocComment()) {
  546. auto& line_info = GetLineInfo(token_info.token_line);
  547. int64_t token_start = line_info.start + token_info.column;
  548. int64_t token_stop = line_info.start + line_info.length;
  549. return source->Text().slice(token_start, token_stop);
  550. }
  551. // Refer back to the source text to preserve oddities like radix or digit
  552. // separators the author included.
  553. if (token_info.kind == TokenKind::IntegerLiteral()) {
  554. auto& line_info = GetLineInfo(token_info.token_line);
  555. int64_t token_start = line_info.start + token_info.column;
  556. return TakeLeadingIntegerLiteral(source->Text().substr(token_start));
  557. }
  558. assert(token_info.kind == TokenKind::Identifier() &&
  559. "Only identifiers have stored text!");
  560. return GetIdentifierText(token_info.id);
  561. }
  562. auto TokenizedBuffer::GetIdentifier(Token token) const -> Identifier {
  563. auto& token_info = GetTokenInfo(token);
  564. assert(token_info.kind == TokenKind::Identifier() &&
  565. "The token must be an identifier!");
  566. return token_info.id;
  567. }
  568. auto TokenizedBuffer::GetIntegerLiteral(Token token) const -> llvm::APInt {
  569. auto& token_info = GetTokenInfo(token);
  570. assert(token_info.kind == TokenKind::IntegerLiteral() &&
  571. "The token must be an integer literal!");
  572. return int_literals[token_info.literal_index];
  573. }
  574. auto TokenizedBuffer::GetMatchedClosingToken(Token opening_token) const
  575. -> Token {
  576. auto& opening_token_info = GetTokenInfo(opening_token);
  577. assert(opening_token_info.kind.IsOpeningSymbol() &&
  578. "The token must be an opening group symbol!");
  579. return opening_token_info.closing_token;
  580. }
  581. auto TokenizedBuffer::GetMatchedOpeningToken(Token closing_token) const
  582. -> Token {
  583. auto& closing_token_info = GetTokenInfo(closing_token);
  584. assert(closing_token_info.kind.IsClosingSymbol() &&
  585. "The token must be an closing group symbol!");
  586. return closing_token_info.opening_token;
  587. }
  588. auto TokenizedBuffer::IsRecoveryToken(Token token) const -> bool {
  589. return GetTokenInfo(token).is_recovery;
  590. }
  591. auto TokenizedBuffer::GetLineNumber(Line line) const -> int {
  592. return line.index + 1;
  593. }
  594. auto TokenizedBuffer::GetIndentColumnNumber(Line line) const -> int {
  595. return GetLineInfo(line).indent + 1;
  596. }
  597. auto TokenizedBuffer::GetIdentifierText(Identifier identifier) const
  598. -> llvm::StringRef {
  599. return identifier_infos[identifier.index].text;
  600. }
  601. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  602. index = std::max(widths.index, index);
  603. kind = std::max(widths.kind, kind);
  604. column = std::max(widths.column, column);
  605. line = std::max(widths.line, line);
  606. indent = std::max(widths.indent, indent);
  607. }
  608. // Compute the printed width of a number. When numbers are printed in decimal,
  609. // the number of digits needed is is one more than the log-base-10 of the value.
  610. // We handle a value of `zero` explicitly.
  611. //
  612. // This routine requires its argument to be *non-negative*.
  613. static auto ComputeDecimalPrintedWidth(int number) -> int {
  614. assert(number >= 0 && "Negative numbers are not supported.");
  615. if (number == 0) {
  616. return 1;
  617. }
  618. return static_cast<int>(std::log10(number)) + 1;
  619. }
  620. auto TokenizedBuffer::GetTokenPrintWidths(Token token) const -> PrintWidths {
  621. PrintWidths widths = {};
  622. widths.index = ComputeDecimalPrintedWidth(token_infos.size());
  623. widths.kind = GetKind(token).Name().size();
  624. widths.line = ComputeDecimalPrintedWidth(GetLineNumber(token));
  625. widths.column = ComputeDecimalPrintedWidth(GetColumnNumber(token));
  626. widths.indent =
  627. ComputeDecimalPrintedWidth(GetIndentColumnNumber(GetLine(token)));
  628. return widths;
  629. }
  630. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  631. if (Tokens().begin() == Tokens().end()) {
  632. return;
  633. }
  634. PrintWidths widths = {};
  635. widths.index = ComputeDecimalPrintedWidth((token_infos.size()));
  636. for (Token token : Tokens()) {
  637. widths.Widen(GetTokenPrintWidths(token));
  638. }
  639. for (Token token : Tokens()) {
  640. PrintToken(output_stream, token, widths);
  641. output_stream << "\n";
  642. }
  643. }
  644. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  645. Token token) const -> void {
  646. PrintToken(output_stream, token, {});
  647. }
  648. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, Token token,
  649. PrintWidths widths) const -> void {
  650. widths.Widen(GetTokenPrintWidths(token));
  651. int token_index = token.index;
  652. auto& token_info = GetTokenInfo(token);
  653. llvm::StringRef token_text = GetTokenText(token);
  654. // Output the main chunk using one format string. We have to do the
  655. // justification manually in order to use the dynamically computed widths
  656. // and get the quotes included.
  657. output_stream << llvm::formatv(
  658. "token: { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  659. "spelling: '{5}'",
  660. llvm::format_decimal(token_index, widths.index),
  661. llvm::right_justify(
  662. (llvm::Twine("'") + token_info.kind.Name() + "'").str(),
  663. widths.kind + 2),
  664. llvm::format_decimal(GetLineNumber(token_info.token_line), widths.line),
  665. llvm::format_decimal(GetColumnNumber(token), widths.column),
  666. llvm::format_decimal(GetIndentColumnNumber(token_info.token_line),
  667. widths.indent),
  668. token_text);
  669. if (token_info.kind == TokenKind::Identifier()) {
  670. output_stream << ", identifier: " << GetIdentifier(token).index;
  671. } else if (token_info.kind.IsOpeningSymbol()) {
  672. output_stream << ", closing_token: " << GetMatchedClosingToken(token).index;
  673. } else if (token_info.kind.IsClosingSymbol()) {
  674. output_stream << ", opening_token: " << GetMatchedOpeningToken(token).index;
  675. }
  676. if (token_info.is_recovery) {
  677. output_stream << ", recovery: true";
  678. }
  679. output_stream << " }";
  680. }
  681. auto TokenizedBuffer::GetLineInfo(Line line) -> LineInfo& {
  682. return line_infos[line.index];
  683. }
  684. auto TokenizedBuffer::GetLineInfo(Line line) const -> const LineInfo& {
  685. return line_infos[line.index];
  686. }
  687. auto TokenizedBuffer::AddLine(LineInfo info) -> Line {
  688. line_infos.push_back(info);
  689. return Line(static_cast<int>(line_infos.size()) - 1);
  690. }
  691. auto TokenizedBuffer::GetTokenInfo(Token token) -> TokenInfo& {
  692. return token_infos[token.index];
  693. }
  694. auto TokenizedBuffer::GetTokenInfo(Token token) const -> const TokenInfo& {
  695. return token_infos[token.index];
  696. }
  697. auto TokenizedBuffer::AddToken(TokenInfo info) -> Token {
  698. token_infos.push_back(info);
  699. return Token(static_cast<int>(token_infos.size()) - 1);
  700. }
  701. } // namespace Carbon