tokenized_buffer.cpp 16 KB

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