tokenized_buffer.cpp 20 KB

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