string_literal.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 "lexer/string_literal.h"
  5. #include "lexer/character_set.h"
  6. #include "llvm/ADT/SmallString.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/ConvertUTF.h"
  9. #include "llvm/Support/ErrorHandling.h"
  10. #include "llvm/Support/FormatVariadic.h"
  11. namespace Carbon {
  12. struct ContentBeforeStringTerminator
  13. : SimpleDiagnostic<ContentBeforeStringTerminator> {
  14. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  15. static constexpr llvm::StringLiteral Message =
  16. "Only whitespace is permitted before the closing `\"\"\"` of a "
  17. "multi-line string.";
  18. };
  19. struct UnicodeEscapeTooLarge : SimpleDiagnostic<UnicodeEscapeTooLarge> {
  20. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  21. static constexpr llvm::StringLiteral Message =
  22. "Code point specified by `\\u{...}` escape is greater than 0x10FFFF.";
  23. };
  24. struct UnicodeEscapeSurrogate : SimpleDiagnostic<UnicodeEscapeSurrogate> {
  25. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  26. static constexpr llvm::StringLiteral Message =
  27. "Code point specified by `\\u{...}` escape is a surrogate character.";
  28. };
  29. struct UnicodeEscapeMissingBracedDigits
  30. : SimpleDiagnostic<UnicodeEscapeMissingBracedDigits> {
  31. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  32. static constexpr llvm::StringLiteral Message =
  33. "Escape sequence `\\u` must be followed by a braced sequence of "
  34. "uppercase hexadecimal digits, for example `\\u{70AD}`.";
  35. };
  36. struct HexadecimalEscapeMissingDigits
  37. : SimpleDiagnostic<HexadecimalEscapeMissingDigits> {
  38. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  39. static constexpr llvm::StringLiteral Message =
  40. "Escape sequence `\\x` must be followed by two "
  41. "uppercase hexadecimal digits, for example `\\x0F`.";
  42. };
  43. struct DecimalEscapeSequence : SimpleDiagnostic<DecimalEscapeSequence> {
  44. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  45. static constexpr llvm::StringLiteral Message =
  46. "Decimal digit follows `\\0` escape sequence. Use `\\x00` instead of "
  47. "`\\0` if the next character is a digit.";
  48. };
  49. struct UnknownEscapeSequence {
  50. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  51. static constexpr const char* Message = "Unrecognized escape sequence `{0}`.";
  52. char first;
  53. auto Format() -> std::string { return llvm::formatv(Message, first).str(); }
  54. };
  55. struct MismatchedIndentInString : SimpleDiagnostic<MismatchedIndentInString> {
  56. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  57. static constexpr llvm::StringLiteral Message =
  58. "Indentation does not match that of the closing \"\"\" in multi-line "
  59. "string literal.";
  60. };
  61. // Find and return the opening characters of a multi-line string literal,
  62. // after any '#'s, including the file type indicator and following newline.
  63. static auto TakeMultiLineStringLiteralPrefix(llvm::StringRef source_text)
  64. -> llvm::StringRef {
  65. llvm::StringRef remaining = source_text;
  66. if (!remaining.consume_front("\"\"\"")) {
  67. return llvm::StringRef();
  68. }
  69. // The rest of the line must be a valid file type indicator: a sequence of
  70. // characters containing neither '#' nor '"' followed by a newline.
  71. remaining = remaining.drop_until(
  72. [](char c) { return c == '"' || c == '#' || c == '\n'; });
  73. if (!remaining.consume_front("\n")) {
  74. return llvm::StringRef();
  75. }
  76. return source_text.take_front(remaining.begin() - source_text.begin());
  77. }
  78. // If source_text begins with a string literal token, extract and return
  79. // information on that token.
  80. auto StringLiteralToken::Lex(llvm::StringRef source_text)
  81. -> llvm::Optional<StringLiteralToken> {
  82. const char* begin = source_text.begin();
  83. int hash_level = 0;
  84. while (source_text.consume_front("#")) {
  85. ++hash_level;
  86. }
  87. llvm::SmallString<16> terminator("\"");
  88. llvm::SmallString<16> escape("\\");
  89. llvm::StringRef multi_line_prefix =
  90. TakeMultiLineStringLiteralPrefix(source_text);
  91. bool multi_line = !multi_line_prefix.empty();
  92. if (multi_line) {
  93. source_text = source_text.drop_front(multi_line_prefix.size());
  94. terminator = "\"\"\"";
  95. } else if (!source_text.consume_front("\"")) {
  96. return llvm::None;
  97. }
  98. // The terminator and escape sequence marker require a number of '#'s
  99. // matching the leading sequence of '#'s.
  100. terminator.resize(terminator.size() + hash_level, '#');
  101. escape.resize(escape.size() + hash_level, '#');
  102. const char* content_begin = source_text.begin();
  103. const char* content_end = content_begin;
  104. while (!source_text.consume_front(terminator)) {
  105. // Let LexError figure out how to recover from an unterminated string
  106. // literal.
  107. if (source_text.empty()) {
  108. return llvm::None;
  109. }
  110. // Consume an escape sequence marker if present.
  111. (void)source_text.consume_front(escape);
  112. // Then consume one more character, either of the content or of an
  113. // escape sequence. This can be a newline in a multi-line string literal.
  114. // This relies on multi-character escape sequences not containing an
  115. // embedded and unescaped terminator or newline.
  116. if (!multi_line && source_text.startswith("\n")) {
  117. return llvm::None;
  118. }
  119. source_text = source_text.substr(1);
  120. content_end = source_text.begin();
  121. }
  122. return StringLiteralToken(
  123. llvm::StringRef(begin, source_text.begin() - begin),
  124. llvm::StringRef(content_begin, content_end - content_begin), hash_level,
  125. multi_line);
  126. }
  127. // Given a string that contains at least one newline, find the indent (the
  128. // leading sequence of horizontal whitespace) of its final line.
  129. static auto ComputeIndentOfFinalLine(llvm::StringRef text) -> llvm::StringRef {
  130. int indent_end = text.size();
  131. for (int i = indent_end - 1; i >= 0; --i) {
  132. if (text[i] == '\n') {
  133. int indent_start = i + 1;
  134. return text.substr(indent_start, indent_end - indent_start);
  135. }
  136. if (!IsSpace(text[i])) {
  137. indent_end = i;
  138. }
  139. }
  140. llvm_unreachable("Given text is required to contain a newline.");
  141. }
  142. namespace {
  143. // The leading whitespace in a multi-line string literal.
  144. struct Indent {
  145. llvm::StringRef indent;
  146. bool has_errors;
  147. };
  148. } // namespace
  149. // Check the literal is indented properly, if it's a multi-line litera.
  150. // Find the leading whitespace that should be removed from each line of a
  151. // multi-line string literal.
  152. static auto CheckIndent(DiagnosticEmitter& emitter, llvm::StringRef text,
  153. llvm::StringRef content) -> Indent {
  154. // Find the leading horizontal whitespace on the final line of this literal.
  155. // Note that for an empty literal, this might not be inside the content.
  156. llvm::StringRef indent = ComputeIndentOfFinalLine(text);
  157. bool has_errors = false;
  158. // The last line is not permitted to contain any content after its
  159. // indentation.
  160. if (indent.end() != content.end()) {
  161. emitter.EmitError<ContentBeforeStringTerminator>();
  162. has_errors = true;
  163. }
  164. return {.indent = indent, .has_errors = has_errors};
  165. }
  166. // Expand a `\u{HHHHHH}` escape sequence into a sequence of UTF-8 code units.
  167. static auto ExpandUnicodeEscapeSequence(DiagnosticEmitter& emitter,
  168. llvm::StringRef digits,
  169. std::string& result) -> bool {
  170. unsigned code_point;
  171. if (digits.getAsInteger(16, code_point) || code_point > 0x10FFFF) {
  172. emitter.EmitError<UnicodeEscapeTooLarge>();
  173. return false;
  174. }
  175. if (code_point >= 0xD800 && code_point < 0xE000) {
  176. emitter.EmitError<UnicodeEscapeSurrogate>();
  177. return false;
  178. }
  179. // Convert the code point to a sequence of UTF-8 code units.
  180. // Every code point fits in 6 UTF-8 code units.
  181. const llvm::UTF32 utf32_code_units[1] = {code_point};
  182. llvm::UTF8 utf8_code_units[6];
  183. const llvm::UTF32* src_pos = utf32_code_units;
  184. llvm::UTF8* dest_pos = utf8_code_units;
  185. llvm::ConversionResult conv_result = llvm::ConvertUTF32toUTF8(
  186. &src_pos, src_pos + 1, &dest_pos, dest_pos + 6, llvm::strictConversion);
  187. if (conv_result != llvm::conversionOK) {
  188. llvm_unreachable("conversion of valid code point to UTF-8 cannot fail");
  189. }
  190. result.insert(result.end(), reinterpret_cast<char*>(utf8_code_units),
  191. reinterpret_cast<char*>(dest_pos));
  192. return true;
  193. }
  194. // Expand an escape sequence, appending the expanded value to the given
  195. // `result` string. `content` is the string content, starting from the first
  196. // character after the escape sequence introducer (for example, the `n` in
  197. // `\n`), and will be updated to remove the leading escape sequence.
  198. static auto ExpandAndConsumeEscapeSequence(DiagnosticEmitter& emitter,
  199. llvm::StringRef& content,
  200. std::string& result) -> bool {
  201. assert(!content.empty() && "should have escaped closing delimiter");
  202. char first = content.front();
  203. content = content.drop_front(1);
  204. switch (first) {
  205. case 't':
  206. result += '\t';
  207. return true;
  208. case 'n':
  209. result += '\n';
  210. return true;
  211. case 'r':
  212. result += '\r';
  213. return true;
  214. case '"':
  215. result += '"';
  216. return true;
  217. case '\'':
  218. result += '\'';
  219. return true;
  220. case '\\':
  221. result += '\\';
  222. return true;
  223. case '0':
  224. result += '\0';
  225. if (!content.empty() && IsDecimalDigit(content.front())) {
  226. emitter.EmitError<DecimalEscapeSequence>();
  227. return false;
  228. }
  229. return true;
  230. case 'x':
  231. if (content.size() >= 2 && IsUpperHexDigit(content[0]) &&
  232. IsUpperHexDigit(content[1])) {
  233. result +=
  234. static_cast<char>(llvm::hexFromNibbles(content[0], content[1]));
  235. content = content.drop_front(2);
  236. return true;
  237. }
  238. emitter.EmitError<HexadecimalEscapeMissingDigits>();
  239. break;
  240. case 'u': {
  241. llvm::StringRef remaining = content;
  242. if (remaining.consume_front("{")) {
  243. llvm::StringRef digits = remaining.take_while(IsUpperHexDigit);
  244. remaining = remaining.drop_front(digits.size());
  245. if (!digits.empty() && remaining.consume_front("}")) {
  246. if (!ExpandUnicodeEscapeSequence(emitter, digits, result)) {
  247. break;
  248. }
  249. content = remaining;
  250. return true;
  251. }
  252. }
  253. emitter.EmitError<UnicodeEscapeMissingBracedDigits>();
  254. break;
  255. }
  256. default:
  257. emitter.EmitError<UnknownEscapeSequence>({.first = first});
  258. break;
  259. }
  260. // If we get here, we didn't recognize this escape sequence and have already
  261. // issued a diagnostic. For error recovery purposes, expand this escape
  262. // sequence to itself, dropping the introducer (for example, `\q` -> `q`).
  263. result += first;
  264. return false;
  265. }
  266. // Expand any escape sequences in the given string literal.
  267. static auto ExpandEscapeSequencesAndRemoveIndent(DiagnosticEmitter& emitter,
  268. llvm::StringRef contents,
  269. int hash_level,
  270. llvm::StringRef indent)
  271. -> StringLiteralToken::ExpandedValue {
  272. std::string result;
  273. result.reserve(contents.size());
  274. bool has_errors = false;
  275. llvm::SmallString<16> escape("\\");
  276. escape.resize(1 + hash_level, '#');
  277. // Process each line of the string literal.
  278. while (true) {
  279. // Every non-empty line (that contains anything other than horizontal
  280. // whitespace) is required to start with the string's indent. For error
  281. // recovery, remove all leading whitespace if the indent doesn't match.
  282. if (!contents.consume_front(indent)) {
  283. contents = contents.drop_while(IsHorizontalWhitespace);
  284. if (!contents.startswith("\n")) {
  285. emitter.EmitError<MismatchedIndentInString>();
  286. has_errors = true;
  287. }
  288. }
  289. // Process the contents of the line.
  290. while (true) {
  291. auto end_of_regular_text = contents.find_first_of("\n\\");
  292. result += contents.substr(0, end_of_regular_text);
  293. contents = contents.substr(end_of_regular_text);
  294. if (contents.empty()) {
  295. return {.result = result, .has_errors = has_errors};
  296. }
  297. if (contents.consume_front("\n")) {
  298. // Trailing whitespace before a newline doesn't contribute to the string
  299. // literal value.
  300. while (!result.empty() && result.back() != '\n' &&
  301. IsSpace(result.back())) {
  302. result.pop_back();
  303. }
  304. result += '\n';
  305. // Move onto to the next line.
  306. break;
  307. }
  308. if (!contents.consume_front(escape)) {
  309. // This is not an escape sequence, just a raw `\`.
  310. result += contents.front();
  311. contents = contents.drop_front(1);
  312. continue;
  313. }
  314. if (contents.consume_front("\n")) {
  315. // An escaped newline ends the line without producing any content and
  316. // without trimming trailing whitespace.
  317. break;
  318. }
  319. // Handle this escape sequence.
  320. if (!ExpandAndConsumeEscapeSequence(emitter, contents, result)) {
  321. has_errors = true;
  322. }
  323. }
  324. }
  325. }
  326. auto StringLiteralToken::ComputeValue(DiagnosticEmitter& emitter) const
  327. -> ExpandedValue {
  328. auto indent = multi_line ? CheckIndent(emitter, text, content) : Indent();
  329. auto result = ExpandEscapeSequencesAndRemoveIndent(emitter, content,
  330. hash_level, indent.indent);
  331. result.has_errors |= indent.has_errors;
  332. return result;
  333. }
  334. } // namespace Carbon