string_helpers.cpp 7.4 KB

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