tokenized_buffer.cpp 29 KB

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