string_helpers.cpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 "common/string_helpers.h"
  5. #include <algorithm>
  6. #include <optional>
  7. #include "common/check.h"
  8. #include "llvm/ADT/StringExtras.h"
  9. #include "llvm/ADT/StringRef.h"
  10. namespace Carbon {
  11. static constexpr llvm::StringRef TripleQuotes = R"(""")";
  12. static constexpr llvm::StringRef HorizontalWhitespaceChars = " \t";
  13. // Carbon only takes uppercase hex input.
  14. static auto FromHex(char c) -> std::optional<char> {
  15. if (c >= '0' && c <= '9') {
  16. return c - '0';
  17. }
  18. if (c >= 'A' && c <= 'F') {
  19. return 10 + c - 'A';
  20. }
  21. return std::nullopt;
  22. }
  23. auto UnescapeStringLiteral(llvm::StringRef source, bool is_block_string)
  24. -> std::optional<std::string> {
  25. std::string ret;
  26. ret.reserve(source.size());
  27. size_t i = 0;
  28. while (i < source.size()) {
  29. char c = source[i];
  30. switch (c) {
  31. case '\\':
  32. ++i;
  33. if (i == source.size()) {
  34. return std::nullopt;
  35. }
  36. switch (source[i]) {
  37. case 'n':
  38. ret.push_back('\n');
  39. break;
  40. case 'r':
  41. ret.push_back('\r');
  42. break;
  43. case 't':
  44. ret.push_back('\t');
  45. break;
  46. case '0':
  47. if (i + 1 < source.size() && llvm::isDigit(source[i + 1])) {
  48. // \0[0-9] is reserved.
  49. return std::nullopt;
  50. }
  51. ret.push_back('\0');
  52. break;
  53. case '"':
  54. ret.push_back('"');
  55. break;
  56. case '\'':
  57. ret.push_back('\'');
  58. break;
  59. case '\\':
  60. ret.push_back('\\');
  61. break;
  62. case 'x': {
  63. i += 2;
  64. if (i >= source.size()) {
  65. return std::nullopt;
  66. }
  67. std::optional<char> c1 = FromHex(source[i - 1]);
  68. std::optional<char> c2 = FromHex(source[i]);
  69. if (c1 == std::nullopt || c2 == std::nullopt) {
  70. return std::nullopt;
  71. }
  72. ret.push_back(16 * *c1 + *c2);
  73. break;
  74. }
  75. case 'u':
  76. FATAL() << "\\u is not yet supported in string literals";
  77. case '\n':
  78. if (!is_block_string) {
  79. return std::nullopt;
  80. }
  81. break;
  82. default:
  83. // Unsupported.
  84. return std::nullopt;
  85. }
  86. break;
  87. case '\t':
  88. // Disallow non-` ` horizontal whitespace:
  89. // https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/lexical_conventions/whitespace.md
  90. // TODO: This doesn't handle unicode whitespace.
  91. return std::nullopt;
  92. default:
  93. ret.push_back(c);
  94. break;
  95. }
  96. ++i;
  97. }
  98. return ret;
  99. }
  100. auto ParseBlockStringLiteral(llvm::StringRef source) -> ErrorOr<std::string> {
  101. llvm::SmallVector<llvm::StringRef> lines;
  102. source.split(lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/true);
  103. if (lines.size() < 2) {
  104. return Error("Too few lines");
  105. }
  106. llvm::StringRef first = lines[0];
  107. if (!first.consume_front(TripleQuotes)) {
  108. return Error("Should start with triple quotes: " + first);
  109. }
  110. first = first.rtrim(HorizontalWhitespaceChars);
  111. // Remaining chars, if any, are a file type indicator.
  112. if (first.find_first_of("\"#") != llvm::StringRef::npos ||
  113. first.find_first_of(HorizontalWhitespaceChars) != llvm::StringRef::npos) {
  114. return Error("Invalid characters in file type indicator: " + first);
  115. }
  116. llvm::StringRef last = lines[lines.size() - 1];
  117. const size_t last_length = last.size();
  118. last = last.ltrim(HorizontalWhitespaceChars);
  119. const size_t indent = last_length - last.size();
  120. if (last != TripleQuotes) {
  121. return Error("Should end with triple quotes: " + last);
  122. }
  123. std::string parsed;
  124. for (size_t i = 1; i < lines.size() - 1; ++i) {
  125. llvm::StringRef line = lines[i];
  126. const size_t first_non_ws =
  127. line.find_first_not_of(HorizontalWhitespaceChars);
  128. if (first_non_ws == llvm::StringRef::npos) {
  129. // Empty or whitespace-only line.
  130. line = "";
  131. } else {
  132. if (first_non_ws < indent) {
  133. return Error("Wrong indent for line: " + line + ", expected " +
  134. llvm::Twine(indent));
  135. }
  136. line = line.drop_front(indent).rtrim(HorizontalWhitespaceChars);
  137. }
  138. // Unescaping with \n appended to handle things like \\<newline>.
  139. llvm::SmallVector<char> buffer;
  140. std::optional<std::string> unescaped = UnescapeStringLiteral(
  141. (line + "\n").toStringRef(buffer), /*is_block_string=*/true);
  142. if (!unescaped.has_value()) {
  143. return Error("Invalid escaping in " + line);
  144. }
  145. // A \<newline> string collapses into nothing.
  146. if (!unescaped->empty()) {
  147. parsed.append(*unescaped);
  148. }
  149. }
  150. return parsed;
  151. }
  152. auto StringRefContainsPointer(llvm::StringRef ref, const char* ptr) -> bool {
  153. auto le = std::less_equal<const char*>();
  154. return le(ref.begin(), ptr) && le(ptr, ref.end());
  155. }
  156. } // namespace Carbon