tokenized_buffer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 "toolchain/lex/tokenized_buffer.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include "common/check.h"
  8. #include "common/string_helpers.h"
  9. #include "llvm/ADT/StringRef.h"
  10. #include "llvm/Support/Format.h"
  11. #include "llvm/Support/FormatVariadic.h"
  12. #include "toolchain/base/value_store.h"
  13. #include "toolchain/diagnostics/diagnostic_emitter.h"
  14. #include "toolchain/lex/character_set.h"
  15. #include "toolchain/lex/numeric_literal.h"
  16. #include "toolchain/lex/string_literal.h"
  17. namespace Carbon::Lex {
  18. auto TokenizedBuffer::GetLine(TokenIndex token) const -> LineIndex {
  19. return FindLineIndex(GetTokenInfo(token).byte_offset());
  20. }
  21. auto TokenizedBuffer::GetLineNumber(TokenIndex token) const -> int {
  22. return GetLineNumber(GetLine(token));
  23. }
  24. auto TokenizedBuffer::GetColumnNumber(TokenIndex token) const -> int {
  25. const auto& token_info = GetTokenInfo(token);
  26. const auto& line_info = GetLineInfo(FindLineIndex(token_info.byte_offset()));
  27. return token_info.byte_offset() - line_info.start + 1;
  28. }
  29. auto TokenizedBuffer::GetEndLoc(TokenIndex token) const
  30. -> std::pair<LineIndex, int> {
  31. auto line = GetLine(token);
  32. int column = GetColumnNumber(token);
  33. auto token_text = GetTokenText(token);
  34. if (auto [before_newline, after_newline] = token_text.rsplit('\n');
  35. before_newline.size() == token_text.size()) {
  36. // Token fits on one line, advance the column number.
  37. column += before_newline.size();
  38. } else {
  39. // Token contains newlines.
  40. line.index += before_newline.count('\n') + 1;
  41. column = 1 + after_newline.size();
  42. }
  43. return {line, column};
  44. }
  45. auto TokenizedBuffer::GetTokenText(TokenIndex token) const -> llvm::StringRef {
  46. const auto& token_info = GetTokenInfo(token);
  47. llvm::StringRef fixed_spelling = token_info.kind().fixed_spelling();
  48. if (!fixed_spelling.empty()) {
  49. return fixed_spelling;
  50. }
  51. if (token_info.kind() == TokenKind::Error) {
  52. return source_->text().substr(token_info.byte_offset(),
  53. token_info.error_length());
  54. }
  55. // Refer back to the source text to preserve oddities like radix or digit
  56. // separators the author included.
  57. if (token_info.kind() == TokenKind::IntLiteral ||
  58. token_info.kind() == TokenKind::RealLiteral) {
  59. std::optional<NumericLiteral> relexed_token =
  60. NumericLiteral::Lex(source_->text().substr(token_info.byte_offset()));
  61. CARBON_CHECK(relexed_token, "Could not reform numeric literal token.");
  62. return relexed_token->text();
  63. }
  64. // Refer back to the source text to find the original spelling, including
  65. // escape sequences etc.
  66. if (token_info.kind() == TokenKind::StringLiteral) {
  67. std::optional<StringLiteral> relexed_token =
  68. StringLiteral::Lex(source_->text().substr(token_info.byte_offset()));
  69. CARBON_CHECK(relexed_token, "Could not reform string literal token.");
  70. return relexed_token->text();
  71. }
  72. // Refer back to the source text to avoid needing to reconstruct the
  73. // spelling from the size.
  74. if (token_info.kind().is_sized_type_literal()) {
  75. llvm::StringRef suffix = source_->text()
  76. .substr(token_info.byte_offset() + 1)
  77. .take_while(IsDecimalDigit);
  78. return llvm::StringRef(suffix.data() - 1, suffix.size() + 1);
  79. }
  80. if (token_info.kind() == TokenKind::FileStart ||
  81. token_info.kind() == TokenKind::FileEnd) {
  82. return llvm::StringRef();
  83. }
  84. CARBON_CHECK(token_info.kind() == TokenKind::Identifier, "{0}",
  85. token_info.kind());
  86. return value_stores_->identifiers().Get(token_info.ident_id());
  87. }
  88. auto TokenizedBuffer::GetIdentifier(TokenIndex token) const -> IdentifierId {
  89. const auto& token_info = GetTokenInfo(token);
  90. CARBON_CHECK(token_info.kind() == TokenKind::Identifier, "{0}",
  91. token_info.kind());
  92. return token_info.ident_id();
  93. }
  94. auto TokenizedBuffer::GetIntLiteral(TokenIndex token) const -> IntId {
  95. const auto& token_info = GetTokenInfo(token);
  96. CARBON_CHECK(token_info.kind() == TokenKind::IntLiteral, "{0}",
  97. token_info.kind());
  98. return token_info.int_id();
  99. }
  100. auto TokenizedBuffer::GetRealLiteral(TokenIndex token) const -> RealId {
  101. const auto& token_info = GetTokenInfo(token);
  102. CARBON_CHECK(token_info.kind() == TokenKind::RealLiteral, "{0}",
  103. token_info.kind());
  104. return token_info.real_id();
  105. }
  106. auto TokenizedBuffer::GetStringLiteralValue(TokenIndex token) const
  107. -> StringLiteralValueId {
  108. const auto& token_info = GetTokenInfo(token);
  109. CARBON_CHECK(token_info.kind() == TokenKind::StringLiteral, "{0}",
  110. token_info.kind());
  111. return token_info.string_literal_id();
  112. }
  113. auto TokenizedBuffer::GetTypeLiteralSize(TokenIndex token) const -> IntId {
  114. const auto& token_info = GetTokenInfo(token);
  115. CARBON_CHECK(token_info.kind().is_sized_type_literal(), "{0}",
  116. token_info.kind());
  117. return token_info.int_id();
  118. }
  119. auto TokenizedBuffer::GetMatchedClosingToken(TokenIndex opening_token) const
  120. -> TokenIndex {
  121. const auto& opening_token_info = GetTokenInfo(opening_token);
  122. CARBON_CHECK(opening_token_info.kind().is_opening_symbol(), "{0}",
  123. opening_token_info.kind());
  124. return opening_token_info.closing_token_index();
  125. }
  126. auto TokenizedBuffer::GetMatchedOpeningToken(TokenIndex closing_token) const
  127. -> TokenIndex {
  128. const auto& closing_token_info = GetTokenInfo(closing_token);
  129. CARBON_CHECK(closing_token_info.kind().is_closing_symbol(), "{0}",
  130. closing_token_info.kind());
  131. return closing_token_info.opening_token_index();
  132. }
  133. auto TokenizedBuffer::IsRecoveryToken(TokenIndex token) const -> bool {
  134. if (recovery_tokens_.empty()) {
  135. return false;
  136. }
  137. return recovery_tokens_[token.index];
  138. }
  139. auto TokenizedBuffer::GetLineNumber(LineIndex line) const -> int {
  140. return line.index + 1;
  141. }
  142. auto TokenizedBuffer::GetNextLine(LineIndex line) const -> LineIndex {
  143. LineIndex next(line.index + 1);
  144. CARBON_DCHECK(static_cast<size_t>(next.index) < line_infos_.size());
  145. return next;
  146. }
  147. auto TokenizedBuffer::GetPrevLine(LineIndex line) const -> LineIndex {
  148. CARBON_CHECK(line.index > 0);
  149. return LineIndex(line.index - 1);
  150. }
  151. auto TokenizedBuffer::GetIndentColumnNumber(LineIndex line) const -> int {
  152. return GetLineInfo(line).indent + 1;
  153. }
  154. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  155. index = std::max(widths.index, index);
  156. kind = std::max(widths.kind, kind);
  157. column = std::max(widths.column, column);
  158. line = std::max(widths.line, line);
  159. indent = std::max(widths.indent, indent);
  160. }
  161. // Compute the printed width of a number. When numbers are printed in decimal,
  162. // the number of digits needed is one more than the log-base-10 of the
  163. // value. We handle a value of `zero` explicitly.
  164. //
  165. // This routine requires its argument to be *non-negative*.
  166. static auto ComputeDecimalPrintedWidth(int number) -> int {
  167. CARBON_CHECK(number >= 0, "Negative numbers are not supported.");
  168. if (number == 0) {
  169. return 1;
  170. }
  171. return static_cast<int>(std::log10(number)) + 1;
  172. }
  173. auto TokenizedBuffer::GetTokenPrintWidths(TokenIndex token) const
  174. -> PrintWidths {
  175. PrintWidths widths = {};
  176. widths.index = ComputeDecimalPrintedWidth(token_infos_.size());
  177. widths.kind = GetKind(token).name().size();
  178. widths.line = ComputeDecimalPrintedWidth(GetLineNumber(token));
  179. widths.column = ComputeDecimalPrintedWidth(GetColumnNumber(token));
  180. widths.indent =
  181. ComputeDecimalPrintedWidth(GetIndentColumnNumber(GetLine(token)));
  182. return widths;
  183. }
  184. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  185. if (tokens().begin() == tokens().end()) {
  186. return;
  187. }
  188. output_stream << "- filename: " << source_->filename() << "\n"
  189. << " tokens: [\n";
  190. PrintWidths widths = {};
  191. widths.index = ComputeDecimalPrintedWidth((token_infos_.size()));
  192. for (TokenIndex token : tokens()) {
  193. widths.Widen(GetTokenPrintWidths(token));
  194. }
  195. for (TokenIndex token : tokens()) {
  196. PrintToken(output_stream, token, widths);
  197. output_stream << "\n";
  198. }
  199. output_stream << " ]\n";
  200. }
  201. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  202. TokenIndex token) const -> void {
  203. PrintToken(output_stream, token, {});
  204. }
  205. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  206. TokenIndex token, PrintWidths widths) const
  207. -> void {
  208. widths.Widen(GetTokenPrintWidths(token));
  209. int token_index = token.index;
  210. const auto& token_info = GetTokenInfo(token);
  211. LineIndex line_index = FindLineIndex(token_info.byte_offset());
  212. llvm::StringRef token_text = GetTokenText(token);
  213. // Output the main chunk using one format string. We have to do the
  214. // justification manually in order to use the dynamically computed widths
  215. // and get the quotes included.
  216. output_stream << llvm::formatv(
  217. " { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  218. "spelling: '{5}'",
  219. llvm::format_decimal(token_index, widths.index),
  220. llvm::right_justify(
  221. llvm::formatv("'{0}'", token_info.kind().name()).str(),
  222. widths.kind + 2),
  223. llvm::format_decimal(GetLineNumber(GetLine(token)), widths.line),
  224. llvm::format_decimal(GetColumnNumber(token), widths.column),
  225. llvm::format_decimal(GetIndentColumnNumber(line_index), widths.indent),
  226. token_text);
  227. switch (token_info.kind()) {
  228. case TokenKind::Identifier:
  229. output_stream << ", identifier: " << GetIdentifier(token).index;
  230. break;
  231. case TokenKind::IntLiteral:
  232. output_stream << ", value: `";
  233. value_stores_->ints()
  234. .Get(GetIntLiteral(token))
  235. .print(output_stream, /*isSigned=*/false);
  236. output_stream << "`";
  237. break;
  238. case TokenKind::RealLiteral:
  239. output_stream << ", value: `"
  240. << value_stores_->reals().Get(GetRealLiteral(token)) << "`";
  241. break;
  242. case TokenKind::StringLiteral:
  243. output_stream << ", value: `"
  244. << value_stores_->string_literal_values().Get(
  245. GetStringLiteralValue(token))
  246. << "`";
  247. break;
  248. default:
  249. if (token_info.kind().is_opening_symbol()) {
  250. output_stream << ", closing_token: "
  251. << GetMatchedClosingToken(token).index;
  252. } else if (token_info.kind().is_closing_symbol()) {
  253. output_stream << ", opening_token: "
  254. << GetMatchedOpeningToken(token).index;
  255. }
  256. break;
  257. }
  258. if (token_info.has_leading_space()) {
  259. output_stream << ", has_leading_space: true";
  260. }
  261. if (IsRecoveryToken(token)) {
  262. output_stream << ", recovery: true";
  263. }
  264. output_stream << " },";
  265. }
  266. // Find the line index corresponding to a specific byte offset within the source
  267. // text for this tokenized buffer.
  268. //
  269. // This takes advantage of the lines being sorted by their starting byte offsets
  270. // to do a binary search for the line that contains the provided offset.
  271. auto TokenizedBuffer::FindLineIndex(int32_t byte_offset) const -> LineIndex {
  272. CARBON_DCHECK(!line_infos_.empty());
  273. const auto* line_it =
  274. std::partition_point(line_infos_.begin(), line_infos_.end(),
  275. [byte_offset](LineInfo line_info) {
  276. return line_info.start <= byte_offset;
  277. });
  278. --line_it;
  279. // If this isn't the first line but it starts past the end of the source, then
  280. // this is a synthetic line added for simplicity of lexing. Step back one
  281. // further to find the last non-synthetic line.
  282. if (line_it != line_infos_.begin() &&
  283. line_it->start == static_cast<int32_t>(source_->text().size())) {
  284. --line_it;
  285. }
  286. CARBON_DCHECK(line_it->start <= byte_offset);
  287. return LineIndex(line_it - line_infos_.begin());
  288. }
  289. auto TokenizedBuffer::GetLineInfo(LineIndex line) -> LineInfo& {
  290. return line_infos_[line.index];
  291. }
  292. auto TokenizedBuffer::GetLineInfo(LineIndex line) const -> const LineInfo& {
  293. return line_infos_[line.index];
  294. }
  295. auto TokenizedBuffer::AddLine(LineInfo info) -> LineIndex {
  296. line_infos_.push_back(info);
  297. return LineIndex(static_cast<int>(line_infos_.size()) - 1);
  298. }
  299. auto TokenizedBuffer::CollectMemUsage(MemUsage& mem_usage,
  300. llvm::StringRef label) const -> void {
  301. mem_usage.Add(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
  302. mem_usage.Add(MemUsage::ConcatLabel(label, "token_infos_"), token_infos_);
  303. mem_usage.Add(MemUsage::ConcatLabel(label, "line_infos_"), line_infos_);
  304. }
  305. auto TokenIterator::Print(llvm::raw_ostream& output) const -> void {
  306. output << token_.index;
  307. }
  308. auto TokenizedBuffer::SourceBufferDiagnosticConverter::ConvertLoc(
  309. const char* loc, ContextFnT /*context_fn*/) const -> DiagnosticLoc {
  310. CARBON_CHECK(StringRefContainsPointer(buffer_->source_->text(), loc),
  311. "location not within buffer");
  312. int32_t offset = loc - buffer_->source_->text().begin();
  313. // Find the first line starting after the given location.
  314. const auto* next_line_it = std::partition_point(
  315. buffer_->line_infos_.begin(), buffer_->line_infos_.end(),
  316. [offset](const LineInfo& line) { return line.start <= offset; });
  317. // Step back one line to find the line containing the given position.
  318. CARBON_CHECK(next_line_it != buffer_->line_infos_.begin(),
  319. "location precedes the start of the first line");
  320. const auto* line_it = std::prev(next_line_it);
  321. int line_number = line_it - buffer_->line_infos_.begin();
  322. int column_number = offset - line_it->start;
  323. // Grab the line from the buffer by slicing from this line to the next
  324. // minus the newline. When on the last line, instead use the start to the end
  325. // of the buffer.
  326. llvm::StringRef text = buffer_->source_->text();
  327. llvm::StringRef line = next_line_it != buffer_->line_infos_.end()
  328. ? text.slice(line_it->start, next_line_it->start)
  329. : text.substr(line_it->start);
  330. // Remove a newline at the end of the line if present.
  331. // TODO: This should expand to remove all vertical whitespace bytes at the
  332. // tail of the line such as CR+LF, etc.
  333. line.consume_back("\n");
  334. return {.filename = buffer_->source_->filename(),
  335. .line = line,
  336. .line_number = line_number + 1,
  337. .column_number = column_number + 1};
  338. }
  339. auto TokenDiagnosticConverter::ConvertLoc(TokenIndex token,
  340. ContextFnT context_fn) const
  341. -> DiagnosticLoc {
  342. // Map the token location into a position within the source buffer.
  343. const auto& token_info = buffer_->GetTokenInfo(token);
  344. const char* token_start =
  345. buffer_->source_->text().begin() + token_info.byte_offset();
  346. // Find the corresponding file location.
  347. // TODO: Should we somehow indicate in the diagnostic location if this token
  348. // is a recovery token that doesn't correspond to the original source?
  349. DiagnosticLoc loc =
  350. TokenizedBuffer::SourceBufferDiagnosticConverter(buffer_).ConvertLoc(
  351. token_start, context_fn);
  352. loc.length = buffer_->GetTokenText(token).size();
  353. return loc;
  354. }
  355. } // namespace Carbon::Lex