string_literal.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. if (!multi_line && source_text.startswith("\n")) {
  111. return llvm::None;
  112. }
  113. // Consume an escape sequence marker if present.
  114. (void)source_text.consume_front(escape);
  115. // Then consume one more character, either of the content or of an
  116. // escape sequence. This relies on multi-character escape sequences
  117. // not containing an embedded and unescaped terminator or newline.
  118. source_text = source_text.substr(1);
  119. content_end = source_text.begin();
  120. }
  121. return StringLiteralToken(
  122. llvm::StringRef(begin, source_text.begin() - begin),
  123. llvm::StringRef(content_begin, content_end - content_begin), hash_level,
  124. multi_line);
  125. }
  126. // Given a string that contains at least one newline, find the indent (the
  127. // leading sequence of horizontal whitespace) of its final line.
  128. static auto ComputeIndentOfFinalLine(llvm::StringRef text) -> llvm::StringRef {
  129. int indent_end = text.size();
  130. for (int i = indent_end - 1; i >= 0; --i) {
  131. if (text[i] == '\n') {
  132. int indent_start = i + 1;
  133. return text.substr(indent_start, indent_end - indent_start);
  134. }
  135. if (!IsSpace(text[i])) {
  136. indent_end = i;
  137. }
  138. }
  139. llvm_unreachable("Given text is required to contain a newline.");
  140. }
  141. namespace {
  142. // The leading whitespace in a multi-line string literal.
  143. struct Indent {
  144. llvm::StringRef indent;
  145. bool has_errors;
  146. };
  147. } // namespace
  148. // Check the literal is indented properly, if it's a multi-line litera.
  149. // Find the leading whitespace that should be removed from each line of a
  150. // multi-line string literal.
  151. static auto CheckIndent(DiagnosticEmitter& emitter, llvm::StringRef text,
  152. llvm::StringRef content) -> Indent {
  153. // Find the leading horizontal whitespace on the final line of this literal.
  154. // Note that for an empty literal, this might not be inside the content.
  155. llvm::StringRef indent = ComputeIndentOfFinalLine(text);
  156. bool has_errors = false;
  157. // The last line is not permitted to contain any content after its
  158. // indentation.
  159. if (indent.end() != content.end()) {
  160. emitter.EmitError<ContentBeforeStringTerminator>();
  161. has_errors = true;
  162. }
  163. return {.indent = indent, .has_errors = has_errors};
  164. }
  165. // Expand a `\u{HHHHHH}` escape sequence into a sequence of UTF-8 code units.
  166. static auto ExpandUnicodeEscapeSequence(DiagnosticEmitter& emitter,
  167. llvm::StringRef digits,
  168. std::string& result) -> bool {
  169. unsigned code_point;
  170. if (digits.getAsInteger(16, code_point) || code_point > 0x10FFFF) {
  171. emitter.EmitError<UnicodeEscapeTooLarge>();
  172. return false;
  173. }
  174. if (code_point >= 0xD800 && code_point < 0xE000) {
  175. emitter.EmitError<UnicodeEscapeSurrogate>();
  176. return false;
  177. }
  178. // Convert the code point to a sequence of UTF-8 code units.
  179. // Every code point fits in 6 UTF-8 code units.
  180. const llvm::UTF32 utf32_code_units[1] = {code_point};
  181. llvm::UTF8 utf8_code_units[6];
  182. const llvm::UTF32* src_pos = utf32_code_units;
  183. llvm::UTF8* dest_pos = utf8_code_units;
  184. llvm::ConversionResult conv_result = llvm::ConvertUTF32toUTF8(
  185. &src_pos, src_pos + 1, &dest_pos, dest_pos + 6, llvm::strictConversion);
  186. if (conv_result != llvm::conversionOK) {
  187. llvm_unreachable("conversion of valid code point to UTF-8 cannot fail");
  188. }
  189. result.insert(result.end(), reinterpret_cast<char*>(utf8_code_units),
  190. reinterpret_cast<char*>(dest_pos));
  191. return true;
  192. }
  193. // Expand an escape sequence, appending the expanded value to the given
  194. // `result` string. `content` is the string content, starting from the first
  195. // character after the escape sequence introducer (for example, the `n` in
  196. // `\n`), and will be updated to remove the leading escape sequence.
  197. static auto ExpandAndConsumeEscapeSequence(DiagnosticEmitter& emitter,
  198. llvm::StringRef& content,
  199. std::string& result) -> bool {
  200. assert(!content.empty() && "should have escaped closing delimiter");
  201. char first = content.front();
  202. content = content.drop_front(1);
  203. switch (first) {
  204. case 't':
  205. result += '\t';
  206. return true;
  207. case 'n':
  208. result += '\n';
  209. return true;
  210. case 'r':
  211. result += '\r';
  212. return true;
  213. case '"':
  214. result += '"';
  215. return true;
  216. case '\'':
  217. result += '\'';
  218. return true;
  219. case '\\':
  220. result += '\\';
  221. return true;
  222. case '0':
  223. result += '\0';
  224. if (!content.empty() && IsDecimalDigit(content.front())) {
  225. emitter.EmitError<DecimalEscapeSequence>();
  226. return false;
  227. }
  228. return true;
  229. case 'x':
  230. if (content.size() >= 2 && IsUpperHexDigit(content[0]) &&
  231. IsUpperHexDigit(content[1])) {
  232. result +=
  233. static_cast<char>(llvm::hexFromNibbles(content[0], content[1]));
  234. content = content.drop_front(2);
  235. return true;
  236. }
  237. emitter.EmitError<HexadecimalEscapeMissingDigits>();
  238. break;
  239. case 'u': {
  240. llvm::StringRef remaining = content;
  241. if (remaining.consume_front("{")) {
  242. llvm::StringRef digits = remaining.take_while(IsUpperHexDigit);
  243. remaining = remaining.drop_front(digits.size());
  244. if (!digits.empty() && remaining.consume_front("}")) {
  245. if (!ExpandUnicodeEscapeSequence(emitter, digits, result)) {
  246. break;
  247. }
  248. content = remaining;
  249. return true;
  250. }
  251. }
  252. emitter.EmitError<UnicodeEscapeMissingBracedDigits>();
  253. break;
  254. }
  255. default:
  256. emitter.EmitError<UnknownEscapeSequence>({.first = first});
  257. break;
  258. }
  259. // If we get here, we didn't recognize this escape sequence and have already
  260. // issued a diagnostic. For error recovery purposes, expand this escape
  261. // sequence to itself, dropping the introducer (for example, `\q` -> `q`).
  262. result += first;
  263. return false;
  264. }
  265. // Expand any escape sequences in the given string literal.
  266. static auto ExpandEscapeSequencesAndRemoveIndent(DiagnosticEmitter& emitter,
  267. llvm::StringRef contents,
  268. int hash_level,
  269. llvm::StringRef indent)
  270. -> StringLiteralToken::ExpandedValue {
  271. std::string result;
  272. result.reserve(contents.size());
  273. bool has_errors = false;
  274. llvm::SmallString<16> escape("\\");
  275. escape.resize(1 + hash_level, '#');
  276. // Process each line of the string literal.
  277. while (true) {
  278. // Every non-empty line (that contains anything other than horizontal
  279. // whitespace) is required to start with the string's indent. For error
  280. // recovery, remove all leading whitespace if the indent doesn't match.
  281. if (!contents.consume_front(indent)) {
  282. contents = contents.drop_while(IsHorizontalWhitespace);
  283. if (!contents.startswith("\n")) {
  284. emitter.EmitError<MismatchedIndentInString>();
  285. has_errors = true;
  286. }
  287. }
  288. // Process the contents of the line.
  289. while (true) {
  290. auto end_of_regular_text = contents.find_first_of("\n\\");
  291. result += contents.substr(0, end_of_regular_text);
  292. contents = contents.substr(end_of_regular_text);
  293. if (contents.empty()) {
  294. return {.result = result, .has_errors = has_errors};
  295. }
  296. if (contents.consume_front("\n")) {
  297. // Trailing whitespace before a newline doesn't contribute to the string
  298. // literal value.
  299. while (!result.empty() && result.back() != '\n' &&
  300. IsSpace(result.back())) {
  301. result.pop_back();
  302. }
  303. result += '\n';
  304. // Move onto to the next line.
  305. break;
  306. }
  307. if (!contents.consume_front(escape)) {
  308. // This is not an escape sequence, just a raw `\`.
  309. result += contents.front();
  310. contents = contents.drop_front(1);
  311. continue;
  312. }
  313. if (contents.consume_front("\n")) {
  314. // An escaped ends the line without producing any content and without
  315. // trimming trailing whitespace.
  316. break;
  317. }
  318. // Handle this escape sequence.
  319. if (!ExpandAndConsumeEscapeSequence(emitter, contents, result)) {
  320. has_errors = true;
  321. }
  322. }
  323. }
  324. }
  325. auto StringLiteralToken::ComputeValue(DiagnosticEmitter& emitter) const
  326. -> ExpandedValue {
  327. auto indent = multi_line ? CheckIndent(emitter, text, content) : Indent();
  328. auto result = ExpandEscapeSequencesAndRemoveIndent(emitter, content,
  329. hash_level, indent.indent);
  330. result.has_errors |= indent.has_errors;
  331. return result;
  332. }
  333. } // namespace Carbon