tokenized_buffer.cpp 14 KB

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