tokenized_buffer.cpp 29 KB

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