string_literal.cpp 13 KB

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