string_helpers.cpp 6.1 KB

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