tokenized_buffer.cpp 16 KB

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