tokenized_buffer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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/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 (has_include_in_dumps_) {
  205. output_stream << " has_include_in_dumps: true\n";
  206. }
  207. if (!dump_sem_ir_ranges_.empty()) {
  208. output_stream << " dump_sem_ir_ranges:\n";
  209. for (auto range : dump_sem_ir_ranges_) {
  210. output_stream << " - {begin: " << range.begin.index
  211. << ", end: " << range.end.index << "}\n";
  212. }
  213. }
  214. }
  215. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  216. TokenIndex token) const -> void {
  217. PrintToken(output_stream, token, {});
  218. }
  219. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  220. TokenIndex token, PrintWidths widths) const
  221. -> void {
  222. widths.Widen(GetTokenPrintWidths(token));
  223. int token_index = token.index;
  224. const auto& token_info = token_infos_.Get(token);
  225. LineIndex line_index = FindLineIndex(token_info.byte_offset());
  226. llvm::StringRef token_text = GetTokenText(token);
  227. // Output the main chunk using one format string. We have to do the
  228. // justification manually in order to use the dynamically computed widths
  229. // and get the quotes included.
  230. output_stream << llvm::formatv(
  231. " - { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  232. "spelling: \"{5}\"",
  233. llvm::format_decimal(token_index, widths.index),
  234. llvm::right_justify(
  235. llvm::formatv("\"{0}\"", token_info.kind().name()).str(),
  236. widths.kind + 2),
  237. llvm::format_decimal(GetLineNumber(token), widths.line),
  238. llvm::format_decimal(GetColumnNumber(token), widths.column),
  239. llvm::format_decimal(GetIndentColumnNumber(line_index), widths.indent),
  240. FormatEscaped(token_text, /*use_hex_escapes=*/true));
  241. switch (token_info.kind()) {
  242. case TokenKind::Identifier:
  243. output_stream << ", identifier: " << GetIdentifier(token).index;
  244. break;
  245. case TokenKind::IntLiteral:
  246. output_stream << ", value: \"";
  247. value_stores_->ints()
  248. .Get(GetIntLiteral(token))
  249. .print(output_stream, /*isSigned=*/false);
  250. output_stream << "\"";
  251. break;
  252. case TokenKind::RealLiteral:
  253. output_stream << ", value: \""
  254. << value_stores_->reals().Get(GetRealLiteral(token))
  255. << "\"";
  256. break;
  257. case TokenKind::StringLiteral:
  258. output_stream << ", value: \""
  259. << FormatEscaped(value_stores_->string_literal_values().Get(
  260. GetStringLiteralValue(token)),
  261. /*use_hex_escapes=*/true)
  262. << "\"";
  263. break;
  264. default:
  265. if (token_info.kind().is_opening_symbol()) {
  266. output_stream << ", closing_token: "
  267. << GetMatchedClosingToken(token).index;
  268. } else if (token_info.kind().is_closing_symbol()) {
  269. output_stream << ", opening_token: "
  270. << GetMatchedOpeningToken(token).index;
  271. }
  272. break;
  273. }
  274. if (token_info.has_leading_space()) {
  275. output_stream << ", has_leading_space: true";
  276. }
  277. if (IsRecoveryToken(token)) {
  278. output_stream << ", recovery: true";
  279. }
  280. output_stream << " }";
  281. }
  282. // Find the line index corresponding to a specific byte offset within the source
  283. // text for this tokenized buffer.
  284. //
  285. // This takes advantage of the lines being sorted by their starting byte offsets
  286. // to do a binary search for the line that contains the provided offset.
  287. auto TokenizedBuffer::FindLineIndex(int32_t byte_offset) const -> LineIndex {
  288. CARBON_DCHECK(line_infos_.size() > 0);
  289. auto line_range = line_infos_.values();
  290. auto line_it =
  291. llvm::partition_point(line_range, [byte_offset](LineInfo line_info) {
  292. return line_info.start <= byte_offset;
  293. });
  294. --line_it;
  295. // If this isn't the first line but it starts past the end of the source, then
  296. // this is a synthetic line added for simplicity of lexing. Step back one
  297. // further to find the last non-synthetic line.
  298. if (line_it != line_range.begin() &&
  299. line_it->start == static_cast<int32_t>(source_->text().size())) {
  300. --line_it;
  301. }
  302. CARBON_DCHECK(line_it->start <= byte_offset);
  303. return LineIndex(line_it - line_range.begin());
  304. }
  305. auto TokenizedBuffer::IsAfterComment(TokenIndex token,
  306. CommentIndex comment_index) const -> bool {
  307. const auto& comment_data = comments_.Get(comment_index);
  308. return token_infos_.Get(token).byte_offset() > comment_data.start;
  309. }
  310. auto TokenizedBuffer::GetCommentText(CommentIndex comment_index) const
  311. -> llvm::StringRef {
  312. const auto& comment_data = comments_.Get(comment_index);
  313. return source_->text().substr(comment_data.start, comment_data.length);
  314. }
  315. auto TokenizedBuffer::AddComment(int32_t indent, int32_t start, int32_t end)
  316. -> void {
  317. if (comments_.size() > 0) {
  318. auto& comment = comments_.Get(CommentIndex(comments_.size() - 1));
  319. if (comment.start + comment.length + indent == start) {
  320. comment.length = end - comment.start;
  321. return;
  322. }
  323. }
  324. comments_.Add({.start = start, .length = end - start});
  325. }
  326. auto TokenizedBuffer::CollectMemUsage(MemUsage& mem_usage,
  327. llvm::StringRef label) const -> void {
  328. mem_usage.Collect(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
  329. mem_usage.Collect(MemUsage::ConcatLabel(label, "token_infos_"), token_infos_);
  330. mem_usage.Collect(MemUsage::ConcatLabel(label, "line_infos_"), line_infos_);
  331. mem_usage.Collect(MemUsage::ConcatLabel(label, "comments_"), comments_);
  332. }
  333. auto TokenizedBuffer::SourcePointerToDiagnosticLoc(const char* loc) const
  334. -> Diagnostics::ConvertedLoc {
  335. CARBON_CHECK(StringRefContainsPointer(source_->text(), loc),
  336. "location not within buffer");
  337. int32_t offset = loc - source_->text().begin();
  338. auto line_range = line_infos_.values();
  339. // Find the first line starting after the given location.
  340. const auto next_line_it = llvm::partition_point(
  341. line_range,
  342. [offset](const LineInfo& line) { return line.start <= offset; });
  343. // Step back one line to find the line containing the given position.
  344. CARBON_CHECK(next_line_it != line_range.begin(),
  345. "location precedes the start of the first line");
  346. const auto line_it = std::prev(next_line_it);
  347. int line_number = line_it - line_range.begin();
  348. int column_number = offset - line_it->start;
  349. // Grab the line from the buffer by slicing from this line to the next
  350. // minus the newline. When on the last line, instead use the start to the end
  351. // of the buffer.
  352. llvm::StringRef text = source_->text();
  353. llvm::StringRef line = next_line_it != line_range.end()
  354. ? text.slice(line_it->start, next_line_it->start)
  355. : text.substr(line_it->start);
  356. // Remove a newline at the end of the line if present.
  357. // TODO: This should expand to remove all vertical whitespace bytes at the
  358. // tail of the line such as CR+LF, etc.
  359. line.consume_back("\n");
  360. return {.loc = {.filename = source_->filename(),
  361. .line = line,
  362. .line_number = line_number + 1,
  363. .column_number = column_number + 1},
  364. .last_byte_offset = offset};
  365. }
  366. auto TokenizedBuffer::TokenToDiagnosticLoc(TokenIndex token) const
  367. -> Diagnostics::ConvertedLoc {
  368. // Map the token location into a position within the source buffer.
  369. const char* token_start =
  370. source_->text().begin() + token_infos_.Get(token).byte_offset();
  371. // Find the corresponding file location.
  372. // TODO: Should we somehow indicate in the diagnostic location if this token
  373. // is a recovery token that doesn't correspond to the original source?
  374. auto converted = SourcePointerToDiagnosticLoc(token_start);
  375. converted.loc.length = GetTokenText(token).size();
  376. return converted;
  377. }
  378. auto TokenizedBuffer::OverlapsWithDumpSemIRRange(
  379. Lex::InclusiveTokenRange range) const -> bool {
  380. CARBON_CHECK(!dump_sem_ir_ranges_.empty());
  381. // Ranges are ordered, so we can decide overlap as soon as we find a range
  382. // that ends after `begin`.
  383. for (auto dump_range : dump_sem_ir_ranges_) {
  384. if (dump_range.end >= range.begin) {
  385. return dump_range.begin <= range.end;
  386. }
  387. }
  388. return false;
  389. }
  390. } // namespace Carbon::Lex