string_literal.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 "toolchain/lexer/string_literal.h"
  5. #include "common/check.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. #include "toolchain/lexer/character_set.h"
  12. namespace Carbon {
  13. using LexerDiagnosticEmitter = DiagnosticEmitter<const char*>;
  14. struct ContentBeforeStringTerminator
  15. : DiagnosticBase<ContentBeforeStringTerminator> {
  16. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  17. static constexpr llvm::StringLiteral Message =
  18. "Only whitespace is permitted before the closing `\"\"\"` of a "
  19. "multi-line string.";
  20. };
  21. struct UnicodeEscapeTooLarge : DiagnosticBase<UnicodeEscapeTooLarge> {
  22. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  23. static constexpr llvm::StringLiteral Message =
  24. "Code point specified by `\\u{...}` escape is greater than 0x10FFFF.";
  25. };
  26. struct UnicodeEscapeSurrogate : DiagnosticBase<UnicodeEscapeSurrogate> {
  27. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  28. static constexpr llvm::StringLiteral Message =
  29. "Code point specified by `\\u{...}` escape is a surrogate character.";
  30. };
  31. struct UnicodeEscapeMissingBracedDigits
  32. : DiagnosticBase<UnicodeEscapeMissingBracedDigits> {
  33. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  34. static constexpr llvm::StringLiteral Message =
  35. "Escape sequence `\\u` must be followed by a braced sequence of "
  36. "uppercase hexadecimal digits, for example `\\u{70AD}`.";
  37. };
  38. struct HexadecimalEscapeMissingDigits
  39. : DiagnosticBase<HexadecimalEscapeMissingDigits> {
  40. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  41. static constexpr llvm::StringLiteral Message =
  42. "Escape sequence `\\x` must be followed by two "
  43. "uppercase hexadecimal digits, for example `\\x0F`.";
  44. };
  45. struct DecimalEscapeSequence : DiagnosticBase<DecimalEscapeSequence> {
  46. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  47. static constexpr llvm::StringLiteral Message =
  48. "Decimal digit follows `\\0` escape sequence. Use `\\x00` instead of "
  49. "`\\0` if the next character is a digit.";
  50. };
  51. struct UnknownEscapeSequence : DiagnosticBase<UnknownEscapeSequence> {
  52. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  53. static constexpr const char* Message = "Unrecognized escape sequence `{0}`.";
  54. auto Format() -> std::string { return llvm::formatv(Message, first).str(); }
  55. char first;
  56. };
  57. struct MismatchedIndentInString : DiagnosticBase<MismatchedIndentInString> {
  58. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  59. static constexpr llvm::StringLiteral Message =
  60. "Indentation does not match that of the closing \"\"\" in multi-line "
  61. "string literal.";
  62. };
  63. struct InvalidHorizontalWhitespaceInString
  64. : DiagnosticBase<InvalidHorizontalWhitespaceInString> {
  65. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-string";
  66. static constexpr llvm::StringLiteral Message =
  67. "Whitespace other than plain space must be expressed with an escape "
  68. "sequence in a string literal.";
  69. };
  70. // Find and return the opening characters of a multi-line string literal,
  71. // after any '#'s, including the file type indicator and following newline.
  72. static auto TakeMultiLineStringLiteralPrefix(llvm::StringRef source_text)
  73. -> llvm::StringRef {
  74. llvm::StringRef remaining = source_text;
  75. if (!remaining.consume_front(R"(""")")) {
  76. return llvm::StringRef();
  77. }
  78. // The rest of the line must be a valid file type indicator: a sequence of
  79. // characters containing neither '#' nor '"' followed by a newline.
  80. remaining = remaining.drop_until(
  81. [](char c) { return c == '"' || c == '#' || c == '\n'; });
  82. if (!remaining.consume_front("\n")) {
  83. return llvm::StringRef();
  84. }
  85. return source_text.take_front(remaining.begin() - source_text.begin());
  86. }
  87. // If source_text begins with a string literal token, extract and return
  88. // information on that token.
  89. auto LexedStringLiteral::Lex(llvm::StringRef source_text)
  90. -> llvm::Optional<LexedStringLiteral> {
  91. const char* begin = source_text.begin();
  92. int hash_level = 0;
  93. while (source_text.consume_front("#")) {
  94. ++hash_level;
  95. }
  96. llvm::SmallString<16> terminator("\"");
  97. llvm::SmallString<16> escape("\\");
  98. llvm::StringRef multi_line_prefix =
  99. TakeMultiLineStringLiteralPrefix(source_text);
  100. bool multi_line = !multi_line_prefix.empty();
  101. if (multi_line) {
  102. source_text = source_text.drop_front(multi_line_prefix.size());
  103. terminator = R"(""")";
  104. } else if (!source_text.consume_front("\"")) {
  105. return llvm::None;
  106. }
  107. // The terminator and escape sequence marker require a number of '#'s
  108. // matching the leading sequence of '#'s.
  109. terminator.resize(terminator.size() + hash_level, '#');
  110. escape.resize(escape.size() + hash_level, '#');
  111. const char* content_begin = source_text.begin();
  112. const char* content_end = content_begin;
  113. while (!source_text.consume_front(terminator)) {
  114. // Let LexError figure out how to recover from an unterminated string
  115. // literal.
  116. if (source_text.empty()) {
  117. return llvm::None;
  118. }
  119. // Consume an escape sequence marker if present.
  120. (void)source_text.consume_front(escape);
  121. // Then consume one more character, either of the content or of an
  122. // escape sequence. This can be a newline in a multi-line string literal.
  123. // This relies on multi-character escape sequences not containing an
  124. // embedded and unescaped terminator or newline.
  125. if (!multi_line && source_text.startswith("\n")) {
  126. return llvm::None;
  127. }
  128. source_text = source_text.substr(1);
  129. content_end = source_text.begin();
  130. }
  131. return LexedStringLiteral(
  132. llvm::StringRef(begin, source_text.begin() - begin),
  133. llvm::StringRef(content_begin, content_end - content_begin), hash_level,
  134. multi_line);
  135. }
  136. // Given a string that contains at least one newline, find the indent (the
  137. // leading sequence of horizontal whitespace) of its final line.
  138. static auto ComputeIndentOfFinalLine(llvm::StringRef text) -> llvm::StringRef {
  139. int indent_end = text.size();
  140. for (int i = indent_end - 1; i >= 0; --i) {
  141. if (text[i] == '\n') {
  142. int indent_start = i + 1;
  143. return text.substr(indent_start, indent_end - indent_start);
  144. }
  145. if (!IsSpace(text[i])) {
  146. indent_end = i;
  147. }
  148. }
  149. llvm_unreachable("Given text is required to contain a newline.");
  150. }
  151. // Check the literal is indented properly, if it's a multi-line litera.
  152. // Find the leading whitespace that should be removed from each line of a
  153. // multi-line string literal.
  154. static auto CheckIndent(LexerDiagnosticEmitter& emitter, llvm::StringRef text,
  155. llvm::StringRef content) -> llvm::StringRef {
  156. // Find the leading horizontal whitespace on the final line of this literal.
  157. // Note that for an empty literal, this might not be inside the content.
  158. llvm::StringRef indent = ComputeIndentOfFinalLine(text);
  159. // The last line is not permitted to contain any content after its
  160. // indentation.
  161. if (indent.end() != content.end()) {
  162. emitter.EmitError<ContentBeforeStringTerminator>(indent.end());
  163. }
  164. return indent;
  165. }
  166. // Expand a `\u{HHHHHH}` escape sequence into a sequence of UTF-8 code units.
  167. static auto ExpandUnicodeEscapeSequence(LexerDiagnosticEmitter& 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>(digits.begin());
  173. return false;
  174. }
  175. if (code_point >= 0xD800 && code_point < 0xE000) {
  176. emitter.EmitError<UnicodeEscapeSurrogate>(digits.begin());
  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(LexerDiagnosticEmitter& emitter,
  199. llvm::StringRef& content,
  200. std::string& result) -> void {
  201. CHECK(!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;
  208. case 'n':
  209. result += '\n';
  210. return;
  211. case 'r':
  212. result += '\r';
  213. return;
  214. case '"':
  215. result += '"';
  216. return;
  217. case '\'':
  218. result += '\'';
  219. return;
  220. case '\\':
  221. result += '\\';
  222. return;
  223. case '0':
  224. result += '\0';
  225. if (!content.empty() && IsDecimalDigit(content.front())) {
  226. emitter.EmitError<DecimalEscapeSequence>(content.begin());
  227. return;
  228. }
  229. return;
  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;
  237. }
  238. emitter.EmitError<HexadecimalEscapeMissingDigits>(content.begin());
  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;
  251. }
  252. }
  253. emitter.EmitError<UnicodeEscapeMissingBracedDigits>(content.begin());
  254. break;
  255. }
  256. default:
  257. emitter.EmitError<UnknownEscapeSequence>(content.begin() - 1,
  258. {.first = first});
  259. break;
  260. }
  261. // If we get here, we didn't recognize this escape sequence and have already
  262. // issued a diagnostic. For error recovery purposes, expand this escape
  263. // sequence to itself, dropping the introducer (for example, `\q` -> `q`).
  264. result += first;
  265. }
  266. // Expand any escape sequences in the given string literal.
  267. static auto ExpandEscapeSequencesAndRemoveIndent(
  268. LexerDiagnosticEmitter& emitter, llvm::StringRef contents, int hash_level,
  269. llvm::StringRef indent) -> std::string {
  270. std::string result;
  271. result.reserve(contents.size());
  272. llvm::SmallString<16> escape("\\");
  273. escape.resize(1 + hash_level, '#');
  274. // Process each line of the string literal.
  275. while (true) {
  276. // Every non-empty line (that contains anything other than horizontal
  277. // whitespace) is required to start with the string's indent. For error
  278. // recovery, remove all leading whitespace if the indent doesn't match.
  279. if (!contents.consume_front(indent)) {
  280. const char* line_start = contents.begin();
  281. contents = contents.drop_while(IsHorizontalWhitespace);
  282. if (!contents.startswith("\n")) {
  283. emitter.EmitError<MismatchedIndentInString>(line_start);
  284. }
  285. }
  286. // Process the contents of the line.
  287. while (true) {
  288. auto end_of_regular_text = contents.find_if([](char c) {
  289. return c == '\n' || c == '\\' ||
  290. (IsHorizontalWhitespace(c) && c != ' ');
  291. });
  292. result += contents.substr(0, end_of_regular_text);
  293. contents = contents.substr(end_of_regular_text);
  294. if (contents.empty()) {
  295. return result;
  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 (IsHorizontalWhitespace(contents.front())) {
  309. // Horizontal whitespace other than ` ` is valid only at the end of a
  310. // line.
  311. CHECK(contents.front() != ' ')
  312. << "should not have stopped at a plain space";
  313. auto after_space = contents.find_if_not(IsHorizontalWhitespace);
  314. if (after_space == llvm::StringRef::npos ||
  315. contents[after_space] != '\n') {
  316. // TODO: Include the source range of the whitespace up to
  317. // `contents.begin() + after_space` in the diagnostic.
  318. emitter.EmitError<InvalidHorizontalWhitespaceInString>(
  319. contents.begin());
  320. // Include the whitespace in the string contents for error recovery.
  321. result += contents.substr(0, after_space);
  322. }
  323. contents = contents.substr(after_space);
  324. continue;
  325. }
  326. if (!contents.consume_front(escape)) {
  327. // This is not an escape sequence, just a raw `\`.
  328. result += contents.front();
  329. contents = contents.drop_front(1);
  330. continue;
  331. }
  332. if (contents.consume_front("\n")) {
  333. // An escaped newline ends the line without producing any content and
  334. // without trimming trailing whitespace.
  335. break;
  336. }
  337. // Handle this escape sequence.
  338. ExpandAndConsumeEscapeSequence(emitter, contents, result);
  339. }
  340. }
  341. }
  342. auto LexedStringLiteral::ComputeValue(LexerDiagnosticEmitter& emitter) const
  343. -> std::string {
  344. llvm::StringRef indent =
  345. multi_line_ ? CheckIndent(emitter, text_, content_) : llvm::StringRef();
  346. return ExpandEscapeSequencesAndRemoveIndent(emitter, content_, hash_level_,
  347. indent);
  348. }
  349. } // namespace Carbon