tokenized_buffer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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(Token token) const -> TokenKind {
  18. return GetTokenInfo(token).kind;
  19. }
  20. auto TokenizedBuffer::GetLine(Token token) const -> Line {
  21. return GetTokenInfo(token).token_line;
  22. }
  23. auto TokenizedBuffer::GetLineNumber(Token token) const -> int {
  24. return GetLineNumber(GetLine(token));
  25. }
  26. auto TokenizedBuffer::GetColumnNumber(Token token) const -> int {
  27. return GetTokenInfo(token).column + 1;
  28. }
  29. auto TokenizedBuffer::GetTokenText(Token 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::IntegerLiteral ||
  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::StartOfFile ||
  71. token_info.kind == TokenKind::EndOfFile) {
  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(Token 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::GetIntegerLiteral(Token token) const -> IntegerId {
  83. const auto& token_info = GetTokenInfo(token);
  84. CARBON_CHECK(token_info.kind == TokenKind::IntegerLiteral) << token_info.kind;
  85. return token_info.integer_id;
  86. }
  87. auto TokenizedBuffer::GetRealLiteral(Token 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(Token token) const -> StringLiteralId {
  93. const auto& token_info = GetTokenInfo(token);
  94. CARBON_CHECK(token_info.kind == TokenKind::StringLiteral) << token_info.kind;
  95. return token_info.string_literal_id;
  96. }
  97. auto TokenizedBuffer::GetTypeLiteralSize(Token token) const
  98. -> const llvm::APInt& {
  99. const auto& token_info = GetTokenInfo(token);
  100. CARBON_CHECK(token_info.kind.is_sized_type_literal()) << token_info.kind;
  101. return value_stores_->integers().Get(token_info.integer_id);
  102. }
  103. auto TokenizedBuffer::GetMatchedClosingToken(Token opening_token) const
  104. -> Token {
  105. const auto& opening_token_info = GetTokenInfo(opening_token);
  106. CARBON_CHECK(opening_token_info.kind.is_opening_symbol())
  107. << opening_token_info.kind;
  108. return opening_token_info.closing_token;
  109. }
  110. auto TokenizedBuffer::GetMatchedOpeningToken(Token closing_token) const
  111. -> Token {
  112. const auto& closing_token_info = GetTokenInfo(closing_token);
  113. CARBON_CHECK(closing_token_info.kind.is_closing_symbol())
  114. << closing_token_info.kind;
  115. return closing_token_info.opening_token;
  116. }
  117. auto TokenizedBuffer::HasLeadingWhitespace(Token token) const -> bool {
  118. auto it = TokenIterator(token);
  119. return it == tokens().begin() || GetTokenInfo(*(it - 1)).has_trailing_space;
  120. }
  121. auto TokenizedBuffer::HasTrailingWhitespace(Token token) const -> bool {
  122. return GetTokenInfo(token).has_trailing_space;
  123. }
  124. auto TokenizedBuffer::IsRecoveryToken(Token token) const -> bool {
  125. return GetTokenInfo(token).is_recovery;
  126. }
  127. auto TokenizedBuffer::GetLineNumber(Line line) const -> int {
  128. return line.index + 1;
  129. }
  130. auto TokenizedBuffer::GetNextLine(Line line) const -> Line {
  131. Line next(line.index + 1);
  132. CARBON_DCHECK(static_cast<size_t>(next.index) < line_infos_.size());
  133. return next;
  134. }
  135. auto TokenizedBuffer::GetPrevLine(Line line) const -> Line {
  136. CARBON_CHECK(line.index > 0);
  137. return Line(line.index - 1);
  138. }
  139. auto TokenizedBuffer::GetIndentColumnNumber(Line line) const -> int {
  140. return GetLineInfo(line).indent + 1;
  141. }
  142. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  143. index = std::max(widths.index, index);
  144. kind = std::max(widths.kind, kind);
  145. column = std::max(widths.column, column);
  146. line = std::max(widths.line, line);
  147. indent = std::max(widths.indent, indent);
  148. }
  149. // Compute the printed width of a number. When numbers are printed in decimal,
  150. // the number of digits needed is is one more than the log-base-10 of the
  151. // value. We handle a value of `zero` explicitly.
  152. //
  153. // This routine requires its argument to be *non-negative*.
  154. static auto ComputeDecimalPrintedWidth(int number) -> int {
  155. CARBON_CHECK(number >= 0) << "Negative numbers are not supported.";
  156. if (number == 0) {
  157. return 1;
  158. }
  159. return static_cast<int>(std::log10(number)) + 1;
  160. }
  161. auto TokenizedBuffer::GetTokenPrintWidths(Token token) const -> PrintWidths {
  162. PrintWidths widths = {};
  163. widths.index = ComputeDecimalPrintedWidth(token_infos_.size());
  164. widths.kind = GetKind(token).name().size();
  165. widths.line = ComputeDecimalPrintedWidth(GetLineNumber(token));
  166. widths.column = ComputeDecimalPrintedWidth(GetColumnNumber(token));
  167. widths.indent =
  168. ComputeDecimalPrintedWidth(GetIndentColumnNumber(GetLine(token)));
  169. return widths;
  170. }
  171. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  172. if (tokens().begin() == tokens().end()) {
  173. return;
  174. }
  175. output_stream << "- filename: " << source_->filename() << "\n"
  176. << " tokens: [\n";
  177. PrintWidths widths = {};
  178. widths.index = ComputeDecimalPrintedWidth((token_infos_.size()));
  179. for (Token token : tokens()) {
  180. widths.Widen(GetTokenPrintWidths(token));
  181. }
  182. for (Token token : tokens()) {
  183. PrintToken(output_stream, token, widths);
  184. output_stream << "\n";
  185. }
  186. output_stream << " ]\n";
  187. }
  188. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  189. Token token) const -> void {
  190. PrintToken(output_stream, token, {});
  191. }
  192. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, Token token,
  193. PrintWidths widths) const -> void {
  194. widths.Widen(GetTokenPrintWidths(token));
  195. int token_index = token.index;
  196. const auto& token_info = GetTokenInfo(token);
  197. llvm::StringRef token_text = GetTokenText(token);
  198. // Output the main chunk using one format string. We have to do the
  199. // justification manually in order to use the dynamically computed widths
  200. // and get the quotes included.
  201. output_stream << llvm::formatv(
  202. " { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  203. "spelling: '{5}'",
  204. llvm::format_decimal(token_index, widths.index),
  205. llvm::right_justify(llvm::formatv("'{0}'", token_info.kind.name()).str(),
  206. widths.kind + 2),
  207. llvm::format_decimal(GetLineNumber(token_info.token_line), widths.line),
  208. llvm::format_decimal(GetColumnNumber(token), widths.column),
  209. llvm::format_decimal(GetIndentColumnNumber(token_info.token_line),
  210. widths.indent),
  211. token_text);
  212. switch (token_info.kind) {
  213. case TokenKind::Identifier:
  214. output_stream << ", identifier: " << GetIdentifier(token).index;
  215. break;
  216. case TokenKind::IntegerLiteral:
  217. output_stream << ", value: `";
  218. value_stores_->integers()
  219. .Get(GetIntegerLiteral(token))
  220. .print(output_stream, /*isSigned=*/false);
  221. output_stream << "`";
  222. break;
  223. case TokenKind::RealLiteral:
  224. output_stream << ", value: `"
  225. << value_stores_->reals().Get(GetRealLiteral(token)) << "`";
  226. break;
  227. case TokenKind::StringLiteral:
  228. output_stream << ", value: `"
  229. << value_stores_->string_literals().Get(
  230. GetStringLiteral(token))
  231. << "`";
  232. break;
  233. default:
  234. if (token_info.kind.is_opening_symbol()) {
  235. output_stream << ", closing_token: "
  236. << GetMatchedClosingToken(token).index;
  237. } else if (token_info.kind.is_closing_symbol()) {
  238. output_stream << ", opening_token: "
  239. << GetMatchedOpeningToken(token).index;
  240. }
  241. break;
  242. }
  243. if (token_info.has_trailing_space) {
  244. output_stream << ", has_trailing_space: true";
  245. }
  246. if (token_info.is_recovery) {
  247. output_stream << ", recovery: true";
  248. }
  249. output_stream << " },";
  250. }
  251. auto TokenizedBuffer::GetLineInfo(Line line) -> LineInfo& {
  252. return line_infos_[line.index];
  253. }
  254. auto TokenizedBuffer::GetLineInfo(Line line) const -> const LineInfo& {
  255. return line_infos_[line.index];
  256. }
  257. auto TokenizedBuffer::AddLine(LineInfo info) -> Line {
  258. line_infos_.push_back(info);
  259. return Line(static_cast<int>(line_infos_.size()) - 1);
  260. }
  261. auto TokenizedBuffer::GetTokenInfo(Token token) -> TokenInfo& {
  262. return token_infos_[token.index];
  263. }
  264. auto TokenizedBuffer::GetTokenInfo(Token token) const -> const TokenInfo& {
  265. return token_infos_[token.index];
  266. }
  267. auto TokenizedBuffer::AddToken(TokenInfo info) -> Token {
  268. token_infos_.push_back(info);
  269. expected_parse_tree_size_ += info.kind.expected_parse_tree_size();
  270. return Token(static_cast<int>(token_infos_.size()) - 1);
  271. }
  272. auto TokenIterator::Print(llvm::raw_ostream& output) const -> void {
  273. output << token_.index;
  274. }
  275. auto TokenizedBuffer::SourceBufferLocationTranslator::GetLocation(
  276. const char* loc) -> DiagnosticLocation {
  277. CARBON_CHECK(StringRefContainsPointer(buffer_->source_->text(), loc))
  278. << "location not within buffer";
  279. int64_t offset = loc - buffer_->source_->text().begin();
  280. // Find the first line starting after the given location. Note that we can't
  281. // inspect `line.length` here because it is not necessarily correct for the
  282. // final line during lexing (but will be correct later for the parse tree).
  283. const auto* line_it = std::partition_point(
  284. buffer_->line_infos_.begin(), buffer_->line_infos_.end(),
  285. [offset](const LineInfo& line) { return line.start <= offset; });
  286. // Step back one line to find the line containing the given position.
  287. CARBON_CHECK(line_it != buffer_->line_infos_.begin())
  288. << "location precedes the start of the first line";
  289. --line_it;
  290. int line_number = line_it - buffer_->line_infos_.begin();
  291. int column_number = offset - line_it->start;
  292. // Start by grabbing the line from the buffer. If the line isn't fully lexed,
  293. // the length will be npos and the line will be grabbed from the known start
  294. // to the end of the buffer; we'll then adjust the length.
  295. llvm::StringRef line =
  296. buffer_->source_->text().substr(line_it->start, line_it->length);
  297. if (line_it->length == static_cast<int32_t>(llvm::StringRef::npos)) {
  298. CARBON_CHECK(line.take_front(column_number).count('\n') == 0)
  299. << "Currently we assume no unlexed newlines prior to the error column, "
  300. "but there was one when erroring at "
  301. << buffer_->source_->filename() << ":" << line_number << ":"
  302. << column_number;
  303. // Look for the next newline since we don't know the length. We can start at
  304. // the column because prior newlines will have been lexed.
  305. auto end_newline_pos = line.find('\n', column_number);
  306. if (end_newline_pos != llvm::StringRef::npos) {
  307. line = line.take_front(end_newline_pos);
  308. }
  309. }
  310. return {.file_name = buffer_->source_->filename(),
  311. .line = line,
  312. .line_number = line_number + 1,
  313. .column_number = column_number + 1};
  314. }
  315. auto TokenLocationTranslator::GetLocation(Token token) -> DiagnosticLocation {
  316. // Map the token location into a position within the source buffer.
  317. const auto& token_info = buffer_->GetTokenInfo(token);
  318. const auto& line_info = buffer_->GetLineInfo(token_info.token_line);
  319. const char* token_start =
  320. buffer_->source_->text().begin() + line_info.start + token_info.column;
  321. // Find the corresponding file location.
  322. // TODO: Should we somehow indicate in the diagnostic location if this token
  323. // is a recovery token that doesn't correspond to the original source?
  324. DiagnosticLocation loc =
  325. TokenizedBuffer::SourceBufferLocationTranslator(buffer_).GetLocation(
  326. token_start);
  327. loc.length = buffer_->GetTokenText(token).size();
  328. return loc;
  329. }
  330. } // namespace Carbon::Lex