string_literal.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. static constexpr char MultiLineIndicator[] = R"(""")";
  71. // Return the number of opening characters of a multi-line string literal,
  72. // after any '#'s, including the file type indicator and following newline.
  73. static auto GetMultiLineStringLiteralPrefixSize(llvm::StringRef source_text)
  74. -> int {
  75. if (!source_text.startswith(MultiLineIndicator)) {
  76. return 0;
  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. auto prefix_end =
  81. source_text.find_first_of("#\n\"", strlen(MultiLineIndicator));
  82. if (prefix_end == llvm::StringRef::npos || source_text[prefix_end] != '\n') {
  83. return 0;
  84. }
  85. // Include the newline on return.
  86. return prefix_end + 1;
  87. }
  88. auto LexedStringLiteral::Lex(llvm::StringRef source_text)
  89. -> llvm::Optional<LexedStringLiteral> {
  90. int64_t cursor = 0;
  91. const int64_t source_text_size = source_text.size();
  92. // Determine the number of hashes prefixing.
  93. while (cursor < source_text_size && source_text[cursor] == '#') {
  94. ++cursor;
  95. }
  96. const int hash_level = cursor;
  97. llvm::SmallString<16> terminator("\"");
  98. llvm::SmallString<16> escape("\\");
  99. const int multi_line_prefix_size =
  100. GetMultiLineStringLiteralPrefixSize(source_text.substr(hash_level));
  101. const bool multi_line = multi_line_prefix_size > 0;
  102. if (multi_line) {
  103. cursor += multi_line_prefix_size;
  104. terminator = MultiLineIndicator;
  105. } else if (cursor < source_text_size && source_text[cursor] == '"') {
  106. ++cursor;
  107. } else {
  108. return llvm::None;
  109. }
  110. const int prefix_len = cursor;
  111. // The terminator and escape sequence marker require a number of '#'s
  112. // matching the leading sequence of '#'s.
  113. terminator.resize(terminator.size() + hash_level, '#');
  114. escape.resize(escape.size() + hash_level, '#');
  115. for (; cursor < source_text_size; ++cursor) {
  116. // This switch and loop structure relies on multi-character terminators and
  117. // escape sequences starting with a predictable character and not containing
  118. // embedded and unescaped terminators or newlines.
  119. switch (source_text[cursor]) {
  120. case '\\':
  121. if (escape.size() == 1 ||
  122. source_text.substr(cursor).startswith(escape)) {
  123. cursor += escape.size();
  124. // If there's either not a character following the escape, or it's a
  125. // single-line string and the escaped character is a newline, we
  126. // should stop here.
  127. if (cursor >= source_text_size ||
  128. (!multi_line && source_text[cursor] == '\n')) {
  129. return llvm::None;
  130. }
  131. }
  132. break;
  133. case '\n':
  134. if (!multi_line) {
  135. return llvm::None;
  136. }
  137. break;
  138. case '\"': {
  139. if (terminator.size() == 1 ||
  140. source_text.substr(cursor).startswith(terminator)) {
  141. llvm::StringRef text =
  142. source_text.substr(0, cursor + terminator.size());
  143. llvm::StringRef content =
  144. source_text.substr(prefix_len, cursor - prefix_len);
  145. return LexedStringLiteral(text, content, hash_level, multi_line);
  146. }
  147. break;
  148. }
  149. }
  150. }
  151. // Let LexError figure out how to recover from an unterminated string
  152. // literal.
  153. return llvm::None;
  154. }
  155. // Given a string that contains at least one newline, find the indent (the
  156. // leading sequence of horizontal whitespace) of its final line.
  157. static auto ComputeIndentOfFinalLine(llvm::StringRef text) -> llvm::StringRef {
  158. int indent_end = text.size();
  159. for (int i = indent_end - 1; i >= 0; --i) {
  160. if (text[i] == '\n') {
  161. int indent_start = i + 1;
  162. return text.substr(indent_start, indent_end - indent_start);
  163. }
  164. if (!IsSpace(text[i])) {
  165. indent_end = i;
  166. }
  167. }
  168. llvm_unreachable("Given text is required to contain a newline.");
  169. }
  170. // Check the literal is indented properly, if it's a multi-line litera.
  171. // Find the leading whitespace that should be removed from each line of a
  172. // multi-line string literal.
  173. static auto CheckIndent(LexerDiagnosticEmitter& emitter, llvm::StringRef text,
  174. llvm::StringRef content) -> llvm::StringRef {
  175. // Find the leading horizontal whitespace on the final line of this literal.
  176. // Note that for an empty literal, this might not be inside the content.
  177. llvm::StringRef indent = ComputeIndentOfFinalLine(text);
  178. // The last line is not permitted to contain any content after its
  179. // indentation.
  180. if (indent.end() != content.end()) {
  181. emitter.EmitError<ContentBeforeStringTerminator>(indent.end());
  182. }
  183. return indent;
  184. }
  185. // Expand a `\u{HHHHHH}` escape sequence into a sequence of UTF-8 code units.
  186. static auto ExpandUnicodeEscapeSequence(LexerDiagnosticEmitter& emitter,
  187. llvm::StringRef digits,
  188. std::string& result) -> bool {
  189. unsigned code_point;
  190. if (digits.getAsInteger(16, code_point) || code_point > 0x10FFFF) {
  191. emitter.EmitError<UnicodeEscapeTooLarge>(digits.begin());
  192. return false;
  193. }
  194. if (code_point >= 0xD800 && code_point < 0xE000) {
  195. emitter.EmitError<UnicodeEscapeSurrogate>(digits.begin());
  196. return false;
  197. }
  198. // Convert the code point to a sequence of UTF-8 code units.
  199. // Every code point fits in 6 UTF-8 code units.
  200. const llvm::UTF32 utf32_code_units[1] = {code_point};
  201. llvm::UTF8 utf8_code_units[6];
  202. const llvm::UTF32* src_pos = utf32_code_units;
  203. llvm::UTF8* dest_pos = utf8_code_units;
  204. llvm::ConversionResult conv_result = llvm::ConvertUTF32toUTF8(
  205. &src_pos, src_pos + 1, &dest_pos, dest_pos + 6, llvm::strictConversion);
  206. if (conv_result != llvm::conversionOK) {
  207. llvm_unreachable("conversion of valid code point to UTF-8 cannot fail");
  208. }
  209. result.insert(result.end(), reinterpret_cast<char*>(utf8_code_units),
  210. reinterpret_cast<char*>(dest_pos));
  211. return true;
  212. }
  213. // Expand an escape sequence, appending the expanded value to the given
  214. // `result` string. `content` is the string content, starting from the first
  215. // character after the escape sequence introducer (for example, the `n` in
  216. // `\n`), and will be updated to remove the leading escape sequence.
  217. static auto ExpandAndConsumeEscapeSequence(LexerDiagnosticEmitter& emitter,
  218. llvm::StringRef& content,
  219. std::string& result) -> void {
  220. CHECK(!content.empty()) << "should have escaped closing delimiter";
  221. char first = content.front();
  222. content = content.drop_front(1);
  223. switch (first) {
  224. case 't':
  225. result += '\t';
  226. return;
  227. case 'n':
  228. result += '\n';
  229. return;
  230. case 'r':
  231. result += '\r';
  232. return;
  233. case '"':
  234. result += '"';
  235. return;
  236. case '\'':
  237. result += '\'';
  238. return;
  239. case '\\':
  240. result += '\\';
  241. return;
  242. case '0':
  243. result += '\0';
  244. if (!content.empty() && IsDecimalDigit(content.front())) {
  245. emitter.EmitError<DecimalEscapeSequence>(content.begin());
  246. return;
  247. }
  248. return;
  249. case 'x':
  250. if (content.size() >= 2 && IsUpperHexDigit(content[0]) &&
  251. IsUpperHexDigit(content[1])) {
  252. result +=
  253. static_cast<char>(llvm::hexFromNibbles(content[0], content[1]));
  254. content = content.drop_front(2);
  255. return;
  256. }
  257. emitter.EmitError<HexadecimalEscapeMissingDigits>(content.begin());
  258. break;
  259. case 'u': {
  260. llvm::StringRef remaining = content;
  261. if (remaining.consume_front("{")) {
  262. llvm::StringRef digits = remaining.take_while(IsUpperHexDigit);
  263. remaining = remaining.drop_front(digits.size());
  264. if (!digits.empty() && remaining.consume_front("}")) {
  265. if (!ExpandUnicodeEscapeSequence(emitter, digits, result)) {
  266. break;
  267. }
  268. content = remaining;
  269. return;
  270. }
  271. }
  272. emitter.EmitError<UnicodeEscapeMissingBracedDigits>(content.begin());
  273. break;
  274. }
  275. default:
  276. emitter.EmitError<UnknownEscapeSequence>(content.begin() - 1,
  277. {.first = first});
  278. break;
  279. }
  280. // If we get here, we didn't recognize this escape sequence and have already
  281. // issued a diagnostic. For error recovery purposes, expand this escape
  282. // sequence to itself, dropping the introducer (for example, `\q` -> `q`).
  283. result += first;
  284. }
  285. // Expand any escape sequences in the given string literal.
  286. static auto ExpandEscapeSequencesAndRemoveIndent(
  287. LexerDiagnosticEmitter& emitter, llvm::StringRef contents, int hash_level,
  288. llvm::StringRef indent) -> std::string {
  289. std::string result;
  290. result.reserve(contents.size());
  291. llvm::SmallString<16> escape("\\");
  292. escape.resize(1 + hash_level, '#');
  293. // Process each line of the string literal.
  294. while (true) {
  295. // Every non-empty line (that contains anything other than horizontal
  296. // whitespace) is required to start with the string's indent. For error
  297. // recovery, remove all leading whitespace if the indent doesn't match.
  298. if (!contents.consume_front(indent)) {
  299. const char* line_start = contents.begin();
  300. contents = contents.drop_while(IsHorizontalWhitespace);
  301. if (!contents.startswith("\n")) {
  302. emitter.EmitError<MismatchedIndentInString>(line_start);
  303. }
  304. }
  305. // Process the contents of the line.
  306. while (true) {
  307. auto end_of_regular_text = contents.find_if([](char c) {
  308. return c == '\n' || c == '\\' ||
  309. (IsHorizontalWhitespace(c) && c != ' ');
  310. });
  311. result += contents.substr(0, end_of_regular_text);
  312. contents = contents.substr(end_of_regular_text);
  313. if (contents.empty()) {
  314. return result;
  315. }
  316. if (contents.consume_front("\n")) {
  317. // Trailing whitespace before a newline doesn't contribute to the string
  318. // literal value.
  319. while (!result.empty() && result.back() != '\n' &&
  320. IsSpace(result.back())) {
  321. result.pop_back();
  322. }
  323. result += '\n';
  324. // Move onto to the next line.
  325. break;
  326. }
  327. if (IsHorizontalWhitespace(contents.front())) {
  328. // Horizontal whitespace other than ` ` is valid only at the end of a
  329. // line.
  330. CHECK(contents.front() != ' ')
  331. << "should not have stopped at a plain space";
  332. auto after_space = contents.find_if_not(IsHorizontalWhitespace);
  333. if (after_space == llvm::StringRef::npos ||
  334. contents[after_space] != '\n') {
  335. // TODO: Include the source range of the whitespace up to
  336. // `contents.begin() + after_space` in the diagnostic.
  337. emitter.EmitError<InvalidHorizontalWhitespaceInString>(
  338. contents.begin());
  339. // Include the whitespace in the string contents for error recovery.
  340. result += contents.substr(0, after_space);
  341. }
  342. contents = contents.substr(after_space);
  343. continue;
  344. }
  345. if (!contents.consume_front(escape)) {
  346. // This is not an escape sequence, just a raw `\`.
  347. result += contents.front();
  348. contents = contents.drop_front(1);
  349. continue;
  350. }
  351. if (contents.consume_front("\n")) {
  352. // An escaped newline ends the line without producing any content and
  353. // without trimming trailing whitespace.
  354. break;
  355. }
  356. // Handle this escape sequence.
  357. ExpandAndConsumeEscapeSequence(emitter, contents, result);
  358. }
  359. }
  360. }
  361. auto LexedStringLiteral::ComputeValue(LexerDiagnosticEmitter& emitter) const
  362. -> std::string {
  363. llvm::StringRef indent =
  364. multi_line_ ? CheckIndent(emitter, text_, content_) : llvm::StringRef();
  365. return ExpandEscapeSequencesAndRemoveIndent(emitter, content_, hash_level_,
  366. indent);
  367. }
  368. } // namespace Carbon