lex_scan_helper.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 "explorer/syntax/lex_scan_helper.h"
  5. #include "common/string_helpers.h"
  6. #include "explorer/syntax/lex_helper.h"
  7. #include "llvm/Support/FormatVariadic.h"
  8. namespace Carbon {
  9. auto StringLexHelper::Advance() -> bool {
  10. CARBON_CHECK(is_eof_ == false);
  11. const char c = YyinputWrapper(yyscanner_);
  12. if (c <= 0) {
  13. context_.RecordSyntaxError("Unexpected end of file");
  14. is_eof_ = true;
  15. return false;
  16. }
  17. str_.push_back(c);
  18. return true;
  19. }
  20. auto ReadHashTags(Carbon::StringLexHelper& scan_helper,
  21. const size_t hashtag_num) -> bool {
  22. for (size_t i = 0; i < hashtag_num; ++i) {
  23. if (!scan_helper.Advance() || scan_helper.last_char() != '#') {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. auto ProcessSingleLineString(llvm::StringRef str,
  30. Carbon::ParseAndLexContext& context,
  31. const size_t hashtag_num)
  32. -> Carbon::Parser::symbol_type {
  33. std::string hashtags(hashtag_num, '#');
  34. const auto str_with_quote = str;
  35. CARBON_CHECK(str.consume_front(hashtags + "\"") &&
  36. str.consume_back("\"" + hashtags));
  37. std::optional<std::string> unescaped =
  38. Carbon::UnescapeStringLiteral(str, hashtag_num);
  39. if (unescaped == std::nullopt) {
  40. return context.RecordSyntaxError(
  41. llvm::formatv("Invalid escaping in string: {0}", str_with_quote));
  42. }
  43. return CARBON_ARG_TOKEN(string_literal, *unescaped);
  44. }
  45. auto ProcessMultiLineString(llvm::StringRef str,
  46. Carbon::ParseAndLexContext& context,
  47. const size_t hashtag_num)
  48. -> Carbon::Parser::symbol_type {
  49. std::string hashtags(hashtag_num, '#');
  50. CARBON_CHECK(str.consume_front(hashtags) && str.consume_back(hashtags));
  51. Carbon::ErrorOr<std::string> block_string =
  52. Carbon::ParseBlockStringLiteral(str, hashtag_num);
  53. if (!block_string.ok()) {
  54. return context.RecordSyntaxError(llvm::formatv(
  55. "Invalid block string: {0}", block_string.error().message()));
  56. }
  57. return CARBON_ARG_TOKEN(string_literal, *block_string);
  58. }
  59. } // namespace Carbon