tokenized_buffer.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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 "lexer/tokenized_buffer.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include <string>
  8. #include "llvm/ADT/StringExtras.h"
  9. #include "llvm/ADT/StringRef.h"
  10. #include "llvm/ADT/StringSwitch.h"
  11. #include "llvm/Support/ErrorHandling.h"
  12. #include "llvm/Support/Format.h"
  13. #include "llvm/Support/FormatVariadic.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. namespace Carbon {
  16. static auto TakeLeadingIntegerLiteral(llvm::StringRef source_text)
  17. -> llvm::StringRef {
  18. return source_text.take_while([](char c) { return llvm::isDigit(c); });
  19. }
  20. struct UnmatchedClosing {
  21. static constexpr llvm::StringLiteral ShortName = "syntax-balanced-delimiters";
  22. static constexpr llvm::StringLiteral Message =
  23. "Closing symbol without a corresponding opening symbol.";
  24. struct Substitutions {};
  25. static auto Format(const Substitutions&) -> std::string {
  26. return Message.str();
  27. }
  28. };
  29. struct MismatchedClosing {
  30. static constexpr llvm::StringLiteral ShortName = "syntax-balanced-delimiters";
  31. static constexpr llvm::StringLiteral Message =
  32. "Closing symbol does not match most recent opening symbol.";
  33. struct Substitutions {};
  34. static auto Format(const Substitutions&) -> std::string {
  35. return Message.str();
  36. }
  37. };
  38. struct UnrecognizedCharacters {
  39. static constexpr llvm::StringLiteral ShortName =
  40. "syntax-unrecognized-characters";
  41. static constexpr llvm::StringLiteral Message =
  42. "Encountered unrecognized characters while parsing.";
  43. struct Substitutions {};
  44. static auto Format(const Substitutions&) -> std::string {
  45. return Message.str();
  46. }
  47. };
  48. // Implementation of the lexer logic itself.
  49. //
  50. // The design is that lexing can loop over the source buffer, consuming it into
  51. // tokens by calling into this API. This class handles the state and breaks down
  52. // the different lexing steps that may be used. It directly updates the provided
  53. // tokenized buffer with the lexed tokens.
  54. class TokenizedBuffer::Lexer {
  55. TokenizedBuffer& buffer;
  56. DiagnosticEmitter& emitter;
  57. Line current_line;
  58. LineInfo* current_line_info;
  59. int current_column = 0;
  60. bool set_indent = false;
  61. llvm::SmallVector<Token, 8> open_groups;
  62. public:
  63. Lexer(TokenizedBuffer& buffer, DiagnosticEmitter& emitter)
  64. : buffer(buffer),
  65. emitter(emitter),
  66. current_line(buffer.AddLine({0, 0, 0})),
  67. current_line_info(&buffer.GetLineInfo(current_line)) {}
  68. auto SkipWhitespace(llvm::StringRef& source_text) -> bool {
  69. while (!source_text.empty()) {
  70. // We only support line-oriented commenting and lex comments as-if they
  71. // were whitespace. Any comment must be the only non-whitespace on the
  72. // line.
  73. if (source_text.startswith("//") && !set_indent) {
  74. // Check if the comment has a special starting sequence of three slashes
  75. // followed by a space. This represents a documentation comment that is
  76. // preserved as a token in the buffer. When parsing, these comments will
  77. // only be accepted in specific parts of the grammar and will be
  78. // associated with the parsed constructs as structure documentation. All
  79. // other comments are simply treated as whitespace.
  80. if (source_text.startswith("///")) {
  81. current_line_info->indent = current_column;
  82. set_indent = true;
  83. buffer.AddToken({.kind = TokenKind::DocComment(),
  84. .token_line = current_line,
  85. .column = current_column});
  86. }
  87. while (!source_text.empty() && source_text.front() != '\n') {
  88. ++current_column;
  89. source_text = source_text.drop_front();
  90. }
  91. if (source_text.empty())
  92. break;
  93. }
  94. switch (source_text.front()) {
  95. default:
  96. // If we find a non-whitespace character without exhausting the
  97. // buffer, return true to continue lexing.
  98. return true;
  99. case '\n':
  100. // New lines are special in order to track line structure.
  101. current_line_info->length = current_column;
  102. // If this is the last character in the source, directly return here
  103. // to avoid creating an empty line.
  104. source_text = source_text.drop_front();
  105. if (source_text.empty())
  106. return false;
  107. // Otherwise, add a line and set up to continue lexing.
  108. current_line = buffer.AddLine(
  109. {current_line_info->start + current_column + 1, 0, 0});
  110. current_line_info = &buffer.GetLineInfo(current_line);
  111. current_column = 0;
  112. set_indent = false;
  113. continue;
  114. case ' ':
  115. case '\t':
  116. // Skip other forms of whitespace while tracking column.
  117. // FIXME: This obviously needs looooots more work to handle unicode
  118. // whitespace as well as special handling to allow better tokenization
  119. // of operators. This is just a stub to check that our column
  120. // management works.
  121. ++current_column;
  122. source_text = source_text.drop_front();
  123. continue;
  124. }
  125. }
  126. assert(source_text.empty() && "Cannot reach here w/o finishing the text!");
  127. // Update the line length as this is also the end of a line.
  128. current_line_info->length = current_column;
  129. return false;
  130. }
  131. auto LexIntegerLiteral(llvm::StringRef& source_text) -> bool {
  132. llvm::StringRef int_text = TakeLeadingIntegerLiteral(source_text);
  133. if (int_text.empty())
  134. return false;
  135. llvm::APInt int_value;
  136. if (int_text.getAsInteger(/*Radix=*/0, int_value))
  137. return false;
  138. int int_column = current_column;
  139. current_column += int_text.size();
  140. source_text = source_text.drop_front(int_text.size());
  141. if (!set_indent) {
  142. current_line_info->indent = int_column;
  143. set_indent = true;
  144. }
  145. auto token = buffer.AddToken({.kind = TokenKind::IntegerLiteral(),
  146. .token_line = current_line,
  147. .column = int_column});
  148. buffer.GetTokenInfo(token).literal_index = buffer.int_literals.size();
  149. buffer.int_literals.push_back(std::move(int_value));
  150. return true;
  151. }
  152. auto LexSymbolToken(llvm::StringRef& source_text) -> bool {
  153. TokenKind kind = llvm::StringSwitch<TokenKind>(source_text)
  154. #define CARBON_SYMBOL_TOKEN(Name, Spelling) \
  155. .StartsWith(Spelling, TokenKind::Name())
  156. #include "lexer/token_registry.def"
  157. .Default(TokenKind::Error());
  158. if (kind == TokenKind::Error())
  159. return false;
  160. if (!set_indent) {
  161. current_line_info->indent = current_column;
  162. set_indent = true;
  163. }
  164. CloseInvalidOpenGroups(kind);
  165. Token token = buffer.AddToken(
  166. {.kind = kind, .token_line = current_line, .column = current_column});
  167. current_column += kind.GetFixedSpelling().size();
  168. source_text = source_text.drop_front(kind.GetFixedSpelling().size());
  169. // Opening symbols just need to be pushed onto our queue of opening groups.
  170. if (kind.IsOpeningSymbol()) {
  171. open_groups.push_back(token);
  172. return true;
  173. }
  174. // Only closing symbols need further special handling.
  175. if (!kind.IsClosingSymbol())
  176. return true;
  177. TokenInfo& closing_token_info = buffer.GetTokenInfo(token);
  178. // Check that there is a matching opening symbol before we consume this as
  179. // a closing symbol.
  180. if (open_groups.empty()) {
  181. closing_token_info.kind = TokenKind::Error();
  182. closing_token_info.error_length = kind.GetFixedSpelling().size();
  183. buffer.has_errors = true;
  184. emitter.EmitError<UnmatchedClosing>(
  185. [](UnmatchedClosing::Substitutions&) {});
  186. // Note that this still returns true as we do consume a symbol.
  187. return true;
  188. }
  189. // Finally can handle a normal closing symbol.
  190. Token opening_token = open_groups.pop_back_val();
  191. TokenInfo& opening_token_info = buffer.GetTokenInfo(opening_token);
  192. opening_token_info.closing_token = token;
  193. closing_token_info.opening_token = opening_token;
  194. return true;
  195. }
  196. // Closes all open groups that cannot remain open across the symbol `K`.
  197. // Users may pass `Error` to close all open groups.
  198. auto CloseInvalidOpenGroups(TokenKind kind) -> void {
  199. if (!kind.IsClosingSymbol() && kind != TokenKind::Error())
  200. return;
  201. while (!open_groups.empty()) {
  202. Token opening_token = open_groups.back();
  203. TokenKind opening_kind = buffer.GetTokenInfo(opening_token).kind;
  204. if (kind == opening_kind.GetClosingSymbol())
  205. return;
  206. open_groups.pop_back();
  207. buffer.has_errors = true;
  208. emitter.EmitError<MismatchedClosing>(
  209. [](MismatchedClosing::Substitutions&) {});
  210. // TODO: do a smarter backwards scan for where to put the closing
  211. // token.
  212. Token closing_token =
  213. buffer.AddToken({.kind = opening_kind.GetClosingSymbol(),
  214. .is_recovery = true,
  215. .token_line = current_line,
  216. .column = current_column});
  217. TokenInfo& opening_token_info = buffer.GetTokenInfo(opening_token);
  218. TokenInfo& closing_token_info = buffer.GetTokenInfo(closing_token);
  219. opening_token_info.closing_token = closing_token;
  220. closing_token_info.opening_token = opening_token;
  221. }
  222. }
  223. auto GetOrCreateIdentifier(llvm::StringRef text) -> Identifier {
  224. auto insert_result = buffer.identifier_map.insert(
  225. {text, Identifier(buffer.identifier_infos.size())});
  226. if (insert_result.second)
  227. buffer.identifier_infos.push_back({text});
  228. return insert_result.first->second;
  229. }
  230. auto LexKeywordOrIdentifier(llvm::StringRef& source_text) -> bool {
  231. if (!llvm::isAlpha(source_text.front()) && source_text.front() != '_')
  232. return false;
  233. if (!set_indent) {
  234. current_line_info->indent = current_column;
  235. set_indent = true;
  236. }
  237. // Take the valid characters off the front of the source buffer.
  238. llvm::StringRef identifier_text = source_text.take_while(
  239. [](char c) { return llvm::isAlnum(c) || c == '_'; });
  240. assert(!identifier_text.empty() && "Must have at least one character!");
  241. int identifier_column = current_column;
  242. current_column += identifier_text.size();
  243. source_text = source_text.drop_front(identifier_text.size());
  244. // Check if the text matches a keyword token, and if so use that.
  245. TokenKind kind = llvm::StringSwitch<TokenKind>(identifier_text)
  246. #define CARBON_KEYWORD_TOKEN(Name, Spelling) .Case(Spelling, TokenKind::Name())
  247. #include "lexer/token_registry.def"
  248. .Default(TokenKind::Error());
  249. if (kind != TokenKind::Error()) {
  250. buffer.AddToken({.kind = kind,
  251. .token_line = current_line,
  252. .column = identifier_column});
  253. return true;
  254. }
  255. // Otherwise we have a generic identifier.
  256. buffer.AddToken({.kind = TokenKind::Identifier(),
  257. .token_line = current_line,
  258. .column = identifier_column,
  259. .id = GetOrCreateIdentifier(identifier_text)});
  260. return true;
  261. }
  262. auto LexError(llvm::StringRef& source_text) -> void {
  263. llvm::StringRef error_text = source_text.take_while([](char c) {
  264. if (llvm::isAlnum(c))
  265. return false;
  266. switch (c) {
  267. case '_':
  268. return false;
  269. case '\t':
  270. return false;
  271. case '\n':
  272. return false;
  273. }
  274. return llvm::StringSwitch<bool>(llvm::StringRef(&c, 1))
  275. #define CARBON_SYMBOL_TOKEN(Name, Spelling) .StartsWith(Spelling, false)
  276. #include "lexer/token_registry.def"
  277. .Default(true);
  278. });
  279. if (error_text.empty()) {
  280. // TODO: Reimplement this to use the lexer properly. In the meantime,
  281. // guarantee that we eat at least one byte.
  282. error_text = source_text.take_front(1);
  283. }
  284. // Longer errors get to be two tokens.
  285. error_text = error_text.substr(0, std::numeric_limits<int32_t>::max());
  286. auto token = buffer.AddToken(
  287. {.kind = TokenKind::Error(),
  288. .token_line = current_line,
  289. .column = current_column,
  290. .error_length = static_cast<int32_t>(error_text.size())});
  291. // TODO: #19 - Need to convert to the diagnostics library.
  292. llvm::errs() << "ERROR: Line " << buffer.GetLineNumber(token) << ", Column "
  293. << buffer.GetColumnNumber(token)
  294. << ": Unrecognized characters!\n";
  295. current_column += error_text.size();
  296. source_text = source_text.drop_front(error_text.size());
  297. buffer.has_errors = true;
  298. }
  299. };
  300. auto TokenizedBuffer::Lex(SourceBuffer& source, DiagnosticEmitter& emitter)
  301. -> TokenizedBuffer {
  302. TokenizedBuffer buffer(source);
  303. Lexer lexer(buffer, emitter);
  304. llvm::StringRef source_text = source.Text();
  305. while (lexer.SkipWhitespace(source_text)) {
  306. // Each time we find non-whitespace characters, try each kind of token we
  307. // support lexing, from simplest to most complex.
  308. if (lexer.LexSymbolToken(source_text))
  309. continue;
  310. if (lexer.LexKeywordOrIdentifier(source_text))
  311. continue;
  312. if (lexer.LexIntegerLiteral(source_text))
  313. continue;
  314. lexer.LexError(source_text);
  315. }
  316. lexer.CloseInvalidOpenGroups(TokenKind::Error());
  317. return buffer;
  318. }
  319. auto TokenizedBuffer::GetKind(Token token) const -> TokenKind {
  320. return GetTokenInfo(token).kind;
  321. }
  322. auto TokenizedBuffer::GetLine(Token token) const -> Line {
  323. return GetTokenInfo(token).token_line;
  324. }
  325. auto TokenizedBuffer::GetLineNumber(Token token) const -> int {
  326. return GetLineNumber(GetLine(token));
  327. }
  328. auto TokenizedBuffer::GetColumnNumber(Token token) const -> int {
  329. return GetTokenInfo(token).column + 1;
  330. }
  331. auto TokenizedBuffer::GetTokenText(Token token) const -> llvm::StringRef {
  332. auto& token_info = GetTokenInfo(token);
  333. llvm::StringRef fixed_spelling = token_info.kind.GetFixedSpelling();
  334. if (!fixed_spelling.empty())
  335. return fixed_spelling;
  336. if (token_info.kind == TokenKind::Error()) {
  337. auto& line_info = GetLineInfo(token_info.token_line);
  338. int64_t token_start = line_info.start + token_info.column;
  339. return source->Text().substr(token_start, token_info.error_length);
  340. }
  341. // Documentation comment tokens refer back to the source text.
  342. if (token_info.kind == TokenKind::DocComment()) {
  343. auto& line_info = GetLineInfo(token_info.token_line);
  344. int64_t token_start = line_info.start + token_info.column;
  345. int64_t token_stop = line_info.start + line_info.length;
  346. return source->Text().slice(token_start, token_stop);
  347. }
  348. // Refer back to the source text to preserve oddities like radix or leading
  349. // 0's the author had.
  350. if (token_info.kind == TokenKind::IntegerLiteral()) {
  351. auto& line_info = GetLineInfo(token_info.token_line);
  352. int64_t token_start = line_info.start + token_info.column;
  353. return TakeLeadingIntegerLiteral(source->Text().substr(token_start));
  354. }
  355. assert(token_info.kind == TokenKind::Identifier() &&
  356. "Only identifiers have stored text!");
  357. return GetIdentifierText(token_info.id);
  358. }
  359. auto TokenizedBuffer::GetIdentifier(Token token) const -> Identifier {
  360. auto& token_info = GetTokenInfo(token);
  361. assert(token_info.kind == TokenKind::Identifier() &&
  362. "The token must be an identifier!");
  363. return token_info.id;
  364. }
  365. auto TokenizedBuffer::GetIntegerLiteral(Token token) const -> llvm::APInt {
  366. auto& token_info = GetTokenInfo(token);
  367. assert(token_info.kind == TokenKind::IntegerLiteral() &&
  368. "The token must be an integer literal!");
  369. return int_literals[token_info.literal_index];
  370. }
  371. auto TokenizedBuffer::GetMatchedClosingToken(Token opening_token) const
  372. -> Token {
  373. auto& opening_token_info = GetTokenInfo(opening_token);
  374. assert(opening_token_info.kind.IsOpeningSymbol() &&
  375. "The token must be an opening group symbol!");
  376. return opening_token_info.closing_token;
  377. }
  378. auto TokenizedBuffer::GetMatchedOpeningToken(Token closing_token) const
  379. -> Token {
  380. auto& closing_token_info = GetTokenInfo(closing_token);
  381. assert(closing_token_info.kind.IsClosingSymbol() &&
  382. "The token must be an closing group symbol!");
  383. return closing_token_info.opening_token;
  384. }
  385. auto TokenizedBuffer::IsRecoveryToken(Token token) const -> bool {
  386. return GetTokenInfo(token).is_recovery;
  387. }
  388. auto TokenizedBuffer::GetLineNumber(Line line) const -> int {
  389. return line.index + 1;
  390. }
  391. auto TokenizedBuffer::GetIndentColumnNumber(Line line) const -> int {
  392. return GetLineInfo(line).indent + 1;
  393. }
  394. auto TokenizedBuffer::GetIdentifierText(Identifier identifier) const
  395. -> llvm::StringRef {
  396. return identifier_infos[identifier.index].text;
  397. }
  398. auto TokenizedBuffer::PrintWidths::Widen(const PrintWidths& widths) -> void {
  399. index = std::max(widths.index, index);
  400. kind = std::max(widths.kind, kind);
  401. column = std::max(widths.column, column);
  402. line = std::max(widths.line, line);
  403. indent = std::max(widths.indent, indent);
  404. }
  405. auto TokenizedBuffer::GetTokenPrintWidths(Token token) const -> PrintWidths {
  406. PrintWidths widths = {};
  407. // Compute the printed width of the various token information. When numbers
  408. // here are printed in decimal, the number of digits needed is is one more than
  409. // the log-base-10 of the value.
  410. widths.index = std::log10(token_infos.size()) + 1;
  411. widths.kind = GetKind(token).Name().size();
  412. widths.line = std::log10(GetLineNumber(token)) + 1;
  413. widths.column = std::log10(GetColumnNumber(token)) + 1;
  414. widths.indent = std::log10(GetIndentColumnNumber(GetLine(token))) + 1;
  415. return widths;
  416. }
  417. auto TokenizedBuffer::Print(llvm::raw_ostream& output_stream) const -> void {
  418. if (Tokens().begin() == Tokens().end())
  419. return;
  420. PrintWidths widths = {};
  421. widths.index = std::log10(token_infos.size()) + 1;
  422. for (Token token : Tokens())
  423. widths.Widen(GetTokenPrintWidths(token));
  424. for (Token token : Tokens()) {
  425. PrintToken(output_stream, token, widths);
  426. output_stream << "\n";
  427. }
  428. }
  429. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream,
  430. Token token) const -> void {
  431. PrintToken(output_stream, token, {});
  432. }
  433. auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, Token token,
  434. PrintWidths widths) const -> void {
  435. widths.Widen(GetTokenPrintWidths(token));
  436. int token_index = token.index;
  437. auto& token_info = GetTokenInfo(token);
  438. llvm::StringRef token_text = GetTokenText(token);
  439. // Output the main chunk using one format string. We have to do the
  440. // justification manually in order to use the dynamically computed widths
  441. // and get the quotes included.
  442. output_stream << llvm::formatv(
  443. "token: { index: {0}, kind: {1}, line: {2}, column: {3}, indent: {4}, "
  444. "spelling: '{5}'",
  445. llvm::format_decimal(token_index, widths.index),
  446. llvm::right_justify(
  447. (llvm::Twine("'") + token_info.kind.Name() + "'").str(),
  448. widths.kind + 2),
  449. llvm::format_decimal(GetLineNumber(token_info.token_line), widths.line),
  450. llvm::format_decimal(GetColumnNumber(token), widths.column),
  451. llvm::format_decimal(GetIndentColumnNumber(token_info.token_line),
  452. widths.indent),
  453. token_text);
  454. if (token_info.kind == TokenKind::Identifier())
  455. output_stream << ", identifier: " << GetIdentifier(token).index;
  456. else if (token_info.kind.IsOpeningSymbol())
  457. output_stream << ", closing_token: " << GetMatchedClosingToken(token).index;
  458. else if (token_info.kind.IsClosingSymbol())
  459. output_stream << ", opening_token: " << GetMatchedOpeningToken(token).index;
  460. if (token_info.is_recovery)
  461. output_stream << ", recovery: true";
  462. output_stream << " }";
  463. }
  464. auto TokenizedBuffer::GetLineInfo(Line line) -> LineInfo& {
  465. return line_infos[line.index];
  466. }
  467. auto TokenizedBuffer::GetLineInfo(Line line) const -> const LineInfo& {
  468. return line_infos[line.index];
  469. }
  470. auto TokenizedBuffer::AddLine(LineInfo info) -> Line {
  471. line_infos.push_back(info);
  472. return Line(line_infos.size() - 1);
  473. }
  474. auto TokenizedBuffer::GetTokenInfo(Token token) -> TokenInfo& {
  475. return token_infos[token.index];
  476. }
  477. auto TokenizedBuffer::GetTokenInfo(Token token) const -> const TokenInfo& {
  478. return token_infos[token.index];
  479. }
  480. auto TokenizedBuffer::AddToken(TokenInfo info) -> Token {
  481. token_infos.push_back(info);
  482. return Token(token_infos.size() - 1);
  483. }
  484. } // namespace Carbon