string_helpers.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. // Creates an error instance with the specified `message`.
  24. static auto MakeError(llvm::Twine message) -> llvm::Expected<std::string> {
  25. return llvm::createStringError(llvm::inconvertibleErrorCode(), message);
  26. }
  27. auto UnescapeStringLiteral(llvm::StringRef source, bool is_block_string)
  28. -> std::optional<std::string> {
  29. std::string ret;
  30. ret.reserve(source.size());
  31. size_t i = 0;
  32. while (i < source.size()) {
  33. char c = source[i];
  34. switch (c) {
  35. case '\\':
  36. ++i;
  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. FATAL() << "\\u is not yet supported in string literals";
  81. case '\n':
  82. if (!is_block_string) {
  83. return std::nullopt;
  84. }
  85. break;
  86. default:
  87. // Unsupported.
  88. return std::nullopt;
  89. }
  90. break;
  91. case '\t':
  92. // Disallow non-` ` horizontal whitespace:
  93. // https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/lexical_conventions/whitespace.md
  94. // TODO: This doesn't handle unicode whitespace.
  95. return std::nullopt;
  96. default:
  97. ret.push_back(c);
  98. break;
  99. }
  100. ++i;
  101. }
  102. return ret;
  103. }
  104. auto ParseBlockStringLiteral(llvm::StringRef source)
  105. -> llvm::Expected<std::string> {
  106. llvm::SmallVector<llvm::StringRef> lines;
  107. source.split(lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/true);
  108. if (lines.size() < 2) {
  109. return MakeError("Too few lines");
  110. }
  111. llvm::StringRef first = lines[0];
  112. if (!first.consume_front(TripleQuotes)) {
  113. return MakeError("Should start with triple quotes: " + first);
  114. }
  115. first = first.rtrim(HorizontalWhitespaceChars);
  116. // Remaining chars, if any, are a file type indicator.
  117. if (first.find_first_of("\"#") != llvm::StringRef::npos ||
  118. first.find_first_of(HorizontalWhitespaceChars) != llvm::StringRef::npos) {
  119. return MakeError("Invalid characters in file type indicator: " + first);
  120. }
  121. llvm::StringRef last = lines[lines.size() - 1];
  122. const size_t last_length = last.size();
  123. last = last.ltrim(HorizontalWhitespaceChars);
  124. const size_t indent = last_length - last.size();
  125. if (last != TripleQuotes) {
  126. return MakeError("Should end with triple quotes: " + last);
  127. }
  128. std::string parsed;
  129. for (size_t i = 1; i < lines.size() - 1; ++i) {
  130. llvm::StringRef line = lines[i];
  131. const size_t first_non_ws =
  132. line.find_first_not_of(HorizontalWhitespaceChars);
  133. if (first_non_ws == llvm::StringRef::npos) {
  134. // Empty or whitespace-only line.
  135. line = "";
  136. } else {
  137. if (first_non_ws < indent) {
  138. return MakeError("Wrong indent for line: " + line + ", expected " +
  139. llvm::Twine(indent));
  140. }
  141. line = line.drop_front(indent).rtrim(HorizontalWhitespaceChars);
  142. }
  143. // Unescaping with \n appended to handle things like \\<newline>.
  144. llvm::SmallVector<char> buffer;
  145. std::optional<std::string> unescaped = UnescapeStringLiteral(
  146. (line + "\n").toStringRef(buffer), /*is_block_string=*/true);
  147. if (!unescaped.has_value()) {
  148. return MakeError("Invalid escaping in " + line);
  149. }
  150. // A \<newline> string collapses into nothing.
  151. if (!unescaped->empty()) {
  152. parsed.append(*unescaped);
  153. }
  154. }
  155. return parsed;
  156. }
  157. auto StringRefContainsPointer(llvm::StringRef ref, const char* ptr) -> bool {
  158. auto le = std::less_equal<const char*>();
  159. return le(ref.begin(), ptr) && le(ptr, ref.end());
  160. }
  161. } // namespace Carbon