tokenized_buffer.cpp 28 KB

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