tokenized_buffer.cpp 16 KB

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